I have an array referance containing hashes (i.e. @AOH)
$arr_ref = [ { 'brand' => 'A',
'supplier' => 'X',
'PO' => '2'
},
{ 'brand' => 'B',
'supplier' => 'Y',
'PO' => '1'
},
{ 'brand' => 'B',
'supplier' => 'X',
'PO' => '2'
},
{ 'brand' => 'A',
'supplier' => 'X',
'PO' => '1'
},
{ 'brand' => 'B',
'supplier' => 'X',
'PO' => '1'
}
];
I want to sort it on the basis of all three keys (i.e. brand, supplier and PO).
Order of sorting should be brand first, then supplier and then finally on PO.
array referance after sorting should be:
$arr_ref = [ { 'brand' => 'A',
'supplier' => 'X',
'PO' => '1'
},
{ 'brand' => 'A',
'supplier' => 'X',
'PO' => '2'
},
{ 'brand' => 'B',
'supplier' => 'X',
'PO' => '1'
},
{ 'brand' => 'B',
'supplier' => 'X',
'PO' => '2'
},
{ 'brand' => 'B',
'supplier' => 'Y',
'PO' => '1'
},
];
Since
<=>andcmpreturn 0 to indicate equality, and that’s false, and because Perl’s logical Boolean operators return the deciding value instead of just 0 or 1, sorting by multiple keys is as easy as stringing multiple comparisons together withoror||:I’m assuming that PO is a numeric field, so you use
<=>for it instead ofcmp.