如何使用perl中的对象对哈希进行排序

yas*_*han 3 perl

我需要通过查看val1这些对象上的公共属性(例如:)来对对象的哈希进行排序(或重新排列).我怎样才能做到这一点?

样品

Per*_*car 6

我将使用基于数组的对象进行说明.

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);
Run Code Online (Sandbox Code Playgroud)

会打印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;
Run Code Online (Sandbox Code Playgroud)