我将使用基于数组的对象进行说明.
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)