提问人:yasara malshan 提问时间:1/15/2019 最后编辑:Daniele Santiyasara malshan 更新时间:1/15/2019 访问量:482
如何在perl中使用对象对哈希进行排序
How can I sort a hash with objects in perl
答:
6赞
Perl Ancar
1/15/2019
#1
我将使用一个基于数组的对象进行说明。
package obj;
sub new { my $class = shift; bless [@_], $class }
sub val1 { my $self = shift; $self->[0] }
sub val2 { my $self = shift; $self->[1] }
sub val3 { my $self = shift; $self->[2] }
package main;
my %hash = (
p => obj->new(4,2,5),
e => obj->new(1,2,5),
z => obj->new(2,2,5),
x => obj->new(3,2,5),
);
# sort the keys of hash according to the 'val1' attribute
my @keys = sort { $hash{$a}->val1 <=> $hash{$b}->val1 } keys %hash;
print join(", ", @keys);
将打印 .e, z, x, p
请注意,如果对象使用基于哈希的表示形式(如示例代码),则可以使用上述代码,也可以直接以哈希形式访问属性。
# sort the keys of hash according to the 'val1' attribute
my @keys = sort { $hash{$a}{val1} <=> $hash{$b}{val1} } keys %hash;
评论
1赞
Grinnz
1/16/2019
另请查看 List::UtilsBy,以便更有效地按可能较慢的方法调用进行排序:use List::UtilsBy 'nsort_by'; my @keys = nsort_by { $hash{$_}->val1 } keys %hash;
评论