The simple way is to write a code for
sort which tells Perl how to compare two elements of the list:
#!/usr/bin/perl
use warnings;
use strict;
use feature qw(say);
my @strings = qw(xxxxxx.2012-50.yyyyy
xxxxxx.2012-51.yyyyy
xxxxxx.2012-52.yyyyy
xxxxxx.2013-1.yyyyy
xxxxxx.2013-2.yyyyy
xxxxxx.2013-3.yyyyy
xxxxxx.2013-4.yyyyy
xxxxxx.2013-10.yyyyy
xxxxxx.2013-11.yyyyy
);
my @sorted = sort {
my ($ay, $an) = $a =~ /\.([0-9]+)-([0-9]+)\./;
my ($by, $bn) = $b =~ /\.([0-9]+)-([0-9]+)\./;
$ay <=> $by or $an <=> $bn
} @string;
say for @sorted;
As this might be rather slow for larger lists, various technics exist to speed it up. One of them is called Orcish Maneuvre:
#!/usr/bin/perl
use warnings;
use strict;
use feature qw(say);
my @strings = qw(xxxxxx.2012-50.yyyyy
xxxxxx.2012-51.yyyyy
xxxxxx.2012-52.yyyyy
xxxxxx.2013-1.yyyyy
xxxxxx.2013-2.yyyyy
xxxxxx.2013-3.yyyyy
xxxxxx.2013-4.yyyyy
xxxxxx.2013-10.yyyyy
xxxxxx.2013-11.yyyyy
);
my %cache;
my @sorted = sort {
($cache{$a} //= generate_key($a))
cmp
($cache{$b} //= generate_key($b))
} @strings;
say for @sorted;
sub generate_key {
my $s = (split /\./, shift)[1];
my ($year, $number) = split /-/, $s;
return $year . sprintf '-%03d', $number;
}
Update: Simple solution added.
-
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.