#!/usr/bin/perl # ----- @mylist = ("gamma", "beta", "alpha", "alf"); @sortedlist = sort @mylist; print "@sortedlist\n"; # ----- sub by_number { # Perl knows that $a and $b are the items to be compared if ($a < $b) { -1 } elsif ($a > $b) { 1 } else { 0 } } @numbers = (3, 6, 18, 12, 2, 4, -3); @sortedlist = sort by_number @numbers; print "@sortedlist\n"; # ----- sub reverse_order { $b <=> $a } @sortedlist = sort reverse_order @numbers; print "@sortedlist\n"; # ----- # This is the default: sub alphabetically { $a cmp $b } sub case_insensitive { "\L$a" cmp "\L$b" } @string_list = ("a", "john", "Mary", "kyle", "Kim", "polly", "B", "brenda"); @alpha_list = sort alphabetically @string_list; @case_list = sort case_insensitive @string_list; print "@alpha_list\n"; print "@case_list\n"; # ----- sub by_value { $hash_table{$b} <=> $hash_table{$a} } %hash_table = ("benny" => 5, "bjorn" => 6, "agnetha" => 9, "anifrid" => 4); @ordered_list = sort by_value keys %hash_table; print "@ordered_list\n"; # ----- sub by_value_and_key { $hash_table{$b} <=> $hash_table{$a} # descending order or $a cmp $b # alphabetically } %hash_table = ("benny" => 6, "bjorn" => 6, "agnetha" => 9, "anifrid" => 4); @ordered_list = sort by_value_and_key keys %hash_table; print "@ordered_list\n"; # -----