Reputation: 409
I have a reference to a list of hashes in Perl, like this:
my $students = [
{ name => "Johnson", age => 19, gpa => 2.5, major => "CS" },
{ name => "Jones", age => 18, gpa => 2.0, major => "IT" },
{ name => "Brown", age => 19, gpa => 2.2, major => "SE" }
];
I need to sort this list ascending and descending by the name
key. I know about the Perl sort
function, but this is a little confusing to me with hashes and multiple keys.
I'm trying this (going off of other questions I've seen on SO):
foreach my $key (sort {$%students->{name}}) {
print $students{$key} . "\n";
}
But it's not quite there (getting syntax errors).
Upvotes: 0
Views: 277
Reputation: 53478
You can't do it with $key
like that, because you have an array(ref), not a hash(ref) in $students
. (And each element of the array is a hash reference).
When you sort
you iterate an list of values comparing elements (e.g. each element of an array, or each key returned by keys %hash
) - each element in turn is assigned to $a
and $b
and compared. If you specify a custom sort, it should return negative, zero or positive based on relative position of elements.
The 'default' is:
sort { $a cmp $b } @list;
Which compares alphanumerically and cmp
returns -1
, 0
or 1
depending on relative ordering. (For numeric comparison we would use $a <=> $b
). We need to iterate the elements of your array (ref) and then compare them by extracting a suitable comparison value.
So:
use strict;
use warnings;
my $students = [
{ name => "Johnson", age => 19, gpa => 2.5, major => "CS" },
{ name => "Jones", age => 18, gpa => 2.0, major => "IT" },
{ name => "Brown", age => 19, gpa => 2.2, major => "SE" }
];
foreach my $hashref ( sort { $a -> {name} cmp $b -> {name} } @$students ) {
print $hashref -> {name},"\n";
}
Upvotes: 5