Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: sorting keys in hash

by dbuckhal (Hermit)
on May 26, 2014 at 00:17 UTC ( #1087381=note: print w/replies, xml ) Need Help??


in reply to sorting keys in hash

Took me a while to come full circle to this, but was trying crazy stuff with splice after moving keys to array! ABORT!!!

So, I realized that once months were translated to numbers, concatenating the day and month in reverse would be easily sortable:

Jul11 = 1107 Jun11 = 1106 Aug13 = 1308 May14 = 1405 etc...

Update

Looked up s///e in the Camel Book and was able to shorten the sortKeys function from:
sub sortKeys { my ( $l_mo, $l_yr ) = $a =~ /(\D+)(\d+)/; my ( $r_mo, $r_yr ) = $b =~ /(\D+)(\d+)/; my $left = $l_yr . $months->{$l_mo}; my $right = $r_yr . $months->{$r_mo}; return ( $left cmp $right ); }
to:
sub sortKeys { ( my $left = $a ) =~ s/(\D+)(\d+)/$2 . $months->{$1}/e; ( my $right = $b ) =~ s/(\D+)(\d+)/$2 . $months->{$1}/e; return ( $left cmp $right ); }

Modified code below:

#!/usr/bin/perl # http://www.perlmonks.org/?node=1087227 use strict; use warnings; my $months = { "Jan" => "01", "Feb" => "02", "Mar" => "03", "Apr" => "04", "May" +=> "05", "Jun" => "06", "Jul" => "07", "Aug" => "08", "Sep" => "09", "Oct" => "10", "Nov" +=> "11", "Dec" => "12", }; my $data = { "Jul11" => 2, "Dec13" => 2, "Jan14" => 2, "Aug13" => 2, "Jun11" => 2, "Apr13" => 2, "Mar12" => 2, "May14" => 2, }; # using regular sort print "before:\n"; foreach my $key (sort keys %$data) { print "Key - $key and b value - $data->{$key}\n"; } # using sortKeys sort print "after\n"; foreach my $key ( sort { sortKeys( $a, $b ) } keys %$data ) { print "Key - $key and b value - $data->{$key}\n"; } sub sortKeys { ( my $left = $a ) =~ s/(\D+)(\d+)/$2 . $months->{$1}/e; ( my $right = $b ) =~ s/(\D+)(\d+)/$2 . $months->{$1}/e; return ( $left cmp $right ); } __output__ $ ./node_id_1087227_hashkey_sort.pl before: Key - Apr13 and b value - 2 Key - Aug13 and b value - 2 Key - Dec13 and b value - 2 Key - Jan14 and b value - 2 Key - Jul11 and b value - 2 Key - Jun11 and b value - 2 Key - Mar12 and b value - 2 Key - May14 and b value - 2 after Key - Jun11 and b value - 2 Key - Jul11 and b value - 2 Key - Mar12 and b value - 2 Key - Apr13 and b value - 2 Key - Aug13 and b value - 2 Key - Dec13 and b value - 2 Key - Jan14 and b value - 2 Key - May14 and b value - 2

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1087381]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2019-10-15 06:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?