#!/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.
In reply to Re: Sort an array of strings based on two fields
by choroba
in thread Sort an array of strings based on two fields
by luca76
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |