-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
6
  • What is {$a}-[0] (etc), with a hyphen ? Do you mean {$a}->[0] (with an arrow)? Commented Aug 16, 2022 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. Commented Aug 16, 2022 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! Commented Aug 16, 2022 at 17:42
  • 1
    Voted to close as a typo Commented Aug 16, 2022 at 17:45
  • I am so sorry @zdim. Thank you! Commented Aug 17, 2022 at 5:24

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.