Hi Tony, I'll try to explain a little more what the code does step by step:
First, we store several hash values in a var called ages,
use Tie::Hash::Sorted; my %ages = ( 'John' => 33, 'Jacob' => 29, 'Jingle' => 15, 'Heimer' => 48, 'Smitz' => 12, );
Then we will have those values: $ages{'John'}=33, $ages{'Jacob'}=29, and so on...
At this point we define a subroutine, that will be assigned through a variable name ($sort_by_numeric_value) later to the module itself.
Nothing is still done because we didn't pass a hash to it, we'll do it later. I have checked Tie::Hash::Sorted and it looks like you can use your own personal sorting subroutine too if you want.
my $sort_by_numeric_value = sub { my $hash = shift; sort {$hash->{$b} <=> $hash->{$a}} keys %$hash ; };
(Normally the subs should be better at the bottom of the code, but I suppose that it's declared there for educational purposes).
The subroutine will "shift" every value listed on the hash we will pass, sorting them accordingly.
At this time we will use a new variable (%sorted_ages) to store the sorted list of 'unsorted' hashes stored in %ages.
Through Tie::Hash::Sorted we specify which hash we want to sort (%hash) and with which method we will sort the values ($sort_by _numeric_value, the subroutine we defined just before).
tie my %sorted_ages, 'Tie::Hash::Sorted', 'Hash' => \ %ages, 'Sort_Routine' => $sort_by_numeric_value;
At last, we return the sorted list of values by the standard output (our screen, normally ;-)). Check that $name belongs to the 'keys' stored in %sorted_ages (John, Jacob...) and that $sorted_ages{$name} stores the value belonging to each key (33,29,...).
for my $name ( keys %sorted_ages ) { print "$name is $sorted_ages{$name} years old.\n"; }
Hope it helps!
In reply to Re^3: meaning for the hash code
by sandboxed
in thread meaning for the hash code
by Tony1
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |