Sorting an Array of Hashes
Code:
#!/usr/bin/perl -wa
use strict;
sub by_age {
return 0 if ( !exists ($a->{"Age"}) );
return 0 if ( !exists ($b->{"Age"}) );
return 0 if ( !exists ($a->{"Name"}) );
return 0 if ( !exists ($b->{"Name"}) );
# sort by age (then by name if age are identical)
return ($a->{"Age"} - $b->{"Age"}) || ($a->{"Name"} cmp $b->{"Name"});
}
if (1) {
my @unsorted_array = ();
# Add some people with assiocated ages onto the array
push (@unsorted_array, {"Name"=>"Jimmy", "Age"=>12});
push (@unsorted_array, {"Name"=>"Timmy", "Age"=>18});
push (@unsorted_array, {"Name"=>"Billy", "Age"=>11});
# sort the people by age
my @sorted_array = sort by_age (@unsorted_array);
for (my $j = 0; $j <= $#sorted_array; $j++) {
print $sorted_array[$j]{"Name"} . " - " . $sorted_array[$j]{"Age"} . "\n";
}
}
Output:
Billy - 11
Jimmy - 12
Timmy - 18
The important part is the by_age subroutine:
When it executes the line:
my @sorted_array = sort by_age (@unsorted_array);
The by_age function gets called with $a and $b as special variables for the elements to be sorted.
(They're global to avoid having the overhead of arguments while sorting...)
Anyway, you get $a and $b which are used like: $a->{"Age"}
And by_age returns a negative, zero or positive number meaning:
$a belongs on the left of $b, $a and $b are equal, $a belongs on the right of $b.
e.g. the sort statement "$a - $b" when $a = 20 and $b = 5 is calculated as:
20 - 5 = 15 (positive) so 20 belongs on the right of 5
That's it folks, enjoy.
|