简体   繁体   English

如何在Perl中对具有多个键的哈希数组进行排序?

[英]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: 我引用了Perl中的哈希列表,如下所示:

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. 我需要按name键对列表进行升序和降序排序。 I know about the Perl sort function, but this is a little confusing to me with hashes and multiple keys. 我知道Perl的sort功能,但是哈希和多个键使我有些困惑。

I'm trying this (going off of other questions I've seen on SO): 我正在尝试这样做(摆脱了我在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 . 不能用$key这样,因为您在$students有一个array(ref),而不是hash(ref)。 (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. 当您sort将迭代一个比较元素值的列表(例如,数组的每个元素或keys %hash返回的每个键)-每个元素又分配给$a$b并进行比较。 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. 其中字母数字进行比较,并且cmp返回-101取决于相对排序。 (For numeric comparison we would use $a <=> $b ). (对于数字比较,我们将使用$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";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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