in reply to sort keys question

OK.
let's assume that %inv looks like this :
(Apple=>10, Peach=>5, Berry=>9, Cobbler=>3, Cherry=>7 )
Now that that's out of the way, let's break things down.
foreach $invnumctr ( sort{$inv{$a} <=> $inv{$b}} keys %inv) { the first thing to worry about is the keys statement. that yields an array :
(Apple, Peach, Berry, Cobbler, Cherry)

so now the sort takes over -- looking the items from the list above, two at a time, putting one into $a and the other into $b, and using them for hash keys. This might look like :
$inv{Apple} <=> $inv{Peach} $inv{Peach} <=> $inv{Berry} $inv{Peach} <=> $inv{Cobbler} ...
and so on. The important thing to remember is that it's still using just the keys to sort on! By the time all is said and done, sort knows that Cobbler's value is less than Peach's value is less than Cherry's value is less than Berry's value is less than Apple's value (no puns, please), and that's what gets passed to foreach. see sort for the full perldoc version, and perlop for the scoop on the spaceship operator.

Replies are listed 'Best First'.
Re: Re: sort keys question (boo)
by tachyon (Chancellor) on Jul 19, 2001 at 03:27 UTC

    The important thing to remember is that it's still using just the keys to sort on!

    Well actually it is sorting numerically on the values not the keys (PS I'm sure this was just a slip of the tongue and would have /msg if you'd been online). Anyway to clarify what boo_radley *meant*

    %inv=( Apple => 10, Peach => 5, Berry => 9, Cobbler => 3, Cherry => 7 ); print "\nSort values numerically in ascending order\n"; foreach $key ( sort {$inv{$a} <=> $inv{$b}} keys %inv) { &print_it } print "\nSort values numerically in descending order\n"; foreach $key ( sort {$inv{$b} <=> $inv{$a}} keys %inv) { &print_it } print "\nSort keys alphabetically in alphabetical order\n"; foreach $key ( sort {$a cmp $b} keys %inv) { &print_it} print "\nNote this is the same as\n"; foreach $key ( sort keys %inv) { &print_it} print "\nSort keys alphabetically in reverse alphabetical order\n"; foreach $key ( sort {$b cmp $a} keys %inv) { &print_it } sub print_it { print "$key\t=> $inv{$key}\n" }

    You will see from the examples that we use <=> for numerical sorts and 'cmp' for alphabetical ones. We sort based on the arguments on each side of these operators. $a is one of the keys whereas $inv{$a} is the value in the $inv hash keyed by $a. You will also note that reversing the position of the arguments reverses the sort order. By default sort uses {$a cmp $b} which is an alphabetical sort in alphabetical order.

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print