Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting alphanumeric hash keys in Perl?

Tags:

sorting

perl

Given the following hash:

%errors = (
    "2013-W9 -> 2013-W12" => 1,
    "2013-W5 -> 2013-W8" => 1,
    "2013-W13 -> 2013-W15" => 1
)

I'm trying to sort it like this (so I can use it in a foreach loop):

%errors = (
    "2013-W5 -> 2013-W8" => 1,
    "2013-W9 -> 2013-W12" => 1,
    "2013-W13 -> 2013-W15" => 1
)

I've tried sort keys %errors and sort{$a <=> $b) keys %errors without success.

How can I fix this problem?

like image 461
Andreas Avatar asked Jan 20 '26 00:01

Andreas


2 Answers

It seems that in this case the CPAN module Sort::Naturally works fine:

use Sort::Naturally qw(nsort);
say $_ for nsort keys %errors;
like image 168
Slaven Rezic Avatar answered Jan 22 '26 23:01

Slaven Rezic


It's not entirely clear what sort order you want, but this approach can easily be extended:

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

my %errors = (
    "2013-W9 -> 2013-W12" => 1,
    "2013-W5 -> 2013-W8" => 1,
    "2013-W13 -> 2013-W15" => 1
);

my @sorted_keys = map { $_->[0] }
  sort { $a->[1] <=> $b->[1] }
  map  { [ $_, /W(\d+)/ ] } keys %errors;

say $_ for @sorted_keys;
like image 40
Dave Cross Avatar answered Jan 22 '26 22:01

Dave Cross



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!