答案 0 :(得分: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);
将打印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;