in reply to Re^2: Sort Hash of hashes
in thread Sort Hash of hashes
The sort{} takes input from the right and sends the same output to the left except in a different order. What goes inside the {} are the "rules" for how to sort the input. $a and $b are special Perl variables that are assigned various values as needed to sort the input. The "return value" of the sort {} should be <0,0,>0 just like the cmp statement does for strings or the "spaceship" operator, <=> does for numbers.#/usr/bin/perl use warnings; use strict; my %hash = (a => 4, b => 6, c => 2); my @sorted_keys = sort keys %hash; print "@sorted_keys\n"; my @sort_by_value = sort{my $A = $hash{$a}; my $B = $hash{$b}; $A <=> $B ## or cmp for strings }keys %hash; print "@sort_by_value\n"; __END__ Prints: a b c # simple key sort c a b # keys sorted by value of keys
|
|---|