Firstly, the months in your hash lookup are mixed case, while in your data they're uppercase. Hash keys are case sensitive.
Secondly, in your by_month function you're getting strings like "APR12" and looking them up in a hash with keys like "Apr". You need to strip the number off before looking them up in the hash.
Here's a fixed version of your script:
#!/usr/bin/env perl
my (@months) = qw(APR12 MAR13 APR11 MAR12 FEB13 APR13);
my @mon = map uc, qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
+);
my $mon;
@{$mon}{@mon} = ( 0 .. $#mon );
sub by_month {
my ($a_mon, $a_yy) = ($a =~ /(...)(..)/);
my ($b_mon, $b_yy) = ($b =~ /(...)(..)/);
$mon->{$a_mon} <=> $mon->{$b_mon};
}
@months = ( sort by_month @months );
print "@months\n";
Note that the above completely ignores the years though. If you want to sort by year first and then month, you could use:
#!/usr/bin/env perl
my (@months) = qw(APR12 MAR13 APR11 MAR12 FEB13 APR13);
my @mon = map uc, qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
+);
my $mon;
@{$mon}{@mon} = ( 0 .. $#mon );
sub by_month {
my ($a_mon, $a_yy) = ($a =~ /(...)(..)/);
my ($b_mon, $b_yy) = ($b =~ /(...)(..)/);
$a_yy <=> $b_yy or $mon->{$a_mon} <=> $mon->{$b_mon};
}
@months = ( sort by_month @months );
print "@months\n";
If you've got a lot of data, the speed could be improved via a Schwartzian transform, but as you're new to Perl, I won't get into that. ;-)
package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.