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?
It seems that in this case the CPAN module Sort::Naturally works fine:
use Sort::Naturally qw(nsort);
say $_ for nsort keys %errors;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With