I need to sort (or re-arrange keys) a hash with objects by looking on a common attribute(eg: val1) on those objects. How can I do that?
I need to sort (or re-arrange keys) a hash with objects by looking on a common attribute(eg: val1) on those objects. How can I do that?
I'm going to use an array-based object for illustration.
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);
Will print e, z, x, p.
Note that if the object uses hash-based representation, as is the case with your example code, you can either use the above code or simply access the attribute directly as hash.
# sort the keys of hash according to the 'val1' attribute
my @keys = sort { $hash{$a}{val1} <=> $hash{$b}{val1} } keys %hash;