简体   繁体   中英

How to sort an array of hashes with multiple keys in Perl?

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).

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 (eg 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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM