Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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.

لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • 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.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2024-04-18 12:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found