Perl: sort hash ref using multiple array ref values

70 Views Asked by At

I have a hash ref with values being an array ref. I would like to sort the hash using multiple values. For example:

{ 'ID' => ['Age', 'Name', 'Start-Date'] }

I would like to sort by: 1) Age; then-by by 2) Start-Date (if Ages are equal). For example:

#!/usr/bin/env perl
use strict;
use warnings;

my $r = {
    'QX' => ['17','Jack','2022-05-31'],
    'ZE' => ['19','Jill','2022-05-31'],
    'RW' => ['17','Aida','2022-08-23'],
    'FX' => ['19','Bill','2022-05-23'],
    'IR' => ['16','Dave','2022-04-01']
};

for my $key (sort {$r->{$a}-[0] <=> $r->{$b}-[0] or $r->{$a}-[2] cmp $r->{$b}-[2]} keys %{$r}) {
    say STDERR "$key: $r->{$key}->[0] : $r->{$key}->[2] : $r->{$key}->[1]";
}

The code above, however, yields incosistent reults.

My expected output (sort by Age followed-by Start-Date) would be:

IR: 16 : 2022-04-01 : Dave
QX: 17 : 2022-05-31 : Jack
RW: 17 : 2022-08-23 : Aida
FX: 19 : 2022-05-23 : Bill
ZE: 19 : 2022-05-31 : Jill
1

There are 1 best solutions below

0
On BEST ANSWER
$r->{$a}-[0]

should be

$r->{$a}->[0]

or just

$r->{$a}[0]   # Arrow optional between indexes.

You could also use

use Sort::Key::Multi qw( uskeysort );

uskeysort { $r->{ $_ }->@[ 0, 2 ] } keys %$r