Sorting custom dates in Perl -
i have hash keys being dates:
my %dates = ( 'may 13, 2015' => 8, 'may 7, 2015' => 1, 'apr 29, 2015' => 2, 'may 12, 2015' => 1, 'apr 16, 2015' => 13, 'may 6, 2015' => 1, ); i'm trying sort them date. i've tried 2 ways:
foreach $k (sort {join('', (split ' ', $a)[2,0,1]) <=> join('', (split ' ', $a)[2,0,1])} keys(%dates)) { print $k . " = " . $dates{$k}; } which doesn't work since month string, , this:
foreach $k (sort {join('', (split ' ', $a)[2,0,1]) cmp join('', (split ' ', $a)[2,0,1])} keys(%dates)) { print $k . " = " . $dates{$k}; } doesn't work either, puts apr first may. has idea on how fix it?
you can parse dates using time::piece
#!/usr/bin/env perl use strict; use warnings; use time::piece; %dates = ( 'may 13, 2015' => 8, 'may 7, 2015' => 1, 'apr 29, 2015' => 2, 'may 12, 2015' => 1, 'apr 16, 2015' => 13, 'may 6, 2015' => 1, ); $k (sort by_date keys %dates) { print "$k => $dates{$k}\n"; } sub by_date { ($ta, $tb) = map time::piece->strptime($_, '%b %d, %y'), $a, $b; $ta <=> $tb; } output:
apr 16, 2015 => 13 apr 29, 2015 => 2 may 6, 2015 => 1 may 7, 2015 => 1 may 12, 2015 => 1 may 13, 2015 => 8
of course, if wanted give benefits of time::piece, along following lines:
#!/usr/bin/env perl use 5.010; use strict; use warnings; %dates = ( 'may 13, 2015' => 8, 'may 7, 2015' => 1, 'apr 29, 2015' => 2, 'may 12, 2015' => 1, 'apr 16, 2015' => 13, 'may 6, 2015' => 1, ); $k (sort by_ugliness keys %dates) { print "$k => $dates{$k}\n"; } sub by_ugliness { state $months = { { $i = 1; map {$_ => $i++} qw(jan feb mar apr may jun jul aug sep oct nov dec) } }; ($ta, $tb) = map [ /\a (\s+) \s+ ([0-9]{1,2}), \s+ ([0-9]{4})\z/x ], $a, $b; ($ta->[2] <=> $tb->[2]) || ($months->{ $ta->[0] } <=> $months->{ $tb->[0]}) || ($ta->[1] <=> $tb->[1]) ; } at point, going start refining pattern match. don't ;-)
Comments
Post a Comment