-1

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
h q
  • 1,168
  • 2
  • 10
  • 23
  • What is `{$a}-[0]` (etc), with a hyphen ? Do you mean `{$a}->[0]` (with an arrow)? – zdim Aug 16 '22 at 17:34
  • @h q: In what place you expect `RW: 17 : 2022-08-23 : Aida` to be printed? Since you mentioned first priority is for `Age` and second is for `Start-Date`. – vkk05 Aug 16 '22 at 17:40
  • Your code is all good, as are the results, once you replace (the typo?) hyphen by the correct arrow... The funny thing is that it runs, and produces results, even with that (non-sensical typo of) hyphen! – zdim Aug 16 '22 at 17:42
  • 1
    Voted to close as a typo – zdim Aug 16 '22 at 17:45
  • I am so sorry @zdim. Thank you! – h q Aug 17 '22 at 05:24
  • @hq All is well, nothing to worry about :) – zdim Aug 17 '22 at 08:36

1 Answers1

2
$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
ikegami
  • 367,544
  • 15
  • 269
  • 518