Reputation: 146
I've done some searching and struggled to find the answer to this one.
Say I have an array of hashes like this..
my @AoH = (
{ 'ip_type' => 1,
'ip_ref' => 0001,
'ip_address' => '192.168.0.1',
'ip_priority' => '100'
},
{ 'ip_type' => 1,
'ip_ref' => 0002,
'ip_address' => '192.168.0.2',
'ip_priority' => '1'
}
);
In context, these are multiple IP addresses, in which I intend to load balance across. The 'ip_priority' value dictates which is first, and subsequently which is second in pirority. primary and backup, basically.
However, I want to order the array elements (aka the hashes) numerically based on the ip priority value within the hash.
So, preferably the above AoH would be...
my @AoH = (
{ 'ip_type' => 1,
'ip_ref' => 0002,
'ip_address' => '192.168.0.2',
'ip_priority' => '1'
},
{ 'ip_type' => 1,
'ip_ref' => 0001,
'ip_address' => '192.168.0.1',
'ip_priority' => '100'
}
);
so $AoH[0]->{ip_priority}
now cotains 1 and $AoH[1]->{ip_priority}
contains 100.
How can I perform a sort in order to achieve the second example above? im struggling to find a workable example!
Upvotes: 1
Views: 111
Reputation: 63892
You can use:
my @sorted = sort {$a->{ip_priority} <=> $b->{ip_priority}} @AoH;
Upvotes: 3