That's a potentially nasty desired sort order. It seems like it could consist of the following components:
- Sort ASCIIbetically the first field, which may be ID, or may be empty.
- Sort numerically the digits of the first part of what looks like a v-string.
- Sort numerically the optional (maybe) digits of the second part of what looks like a v-string.
- Sort numerically the optional (obviously) digits of the third part of what looks like a v-string.
- Sort numerically the digits that follow the optional "ID" characters. (This part of the construct is optional).
- Sort ASCIIbetically the field that looks like ABC, which seems never to be optional, but is preceded by a field that is optional.
That's a mess. But once you break the input into its individual components the sorting becomes pretty simple.
my @data = qw/
ID12-ABC-5.1
ID9-ABC-5.1
ID3-ABC-6.1
ABC-5.1
ID12-ABC-5.1.5
ID15-ABC-6.1
ABC-6.1
ID5-ABC-5.1
ID5-ABC-5.1.5
ABC-5.1.5
/;
my @sorted = do{
no warnings 'uninitialized';
map { $_->[-1] } sort{
$b->[0] cmp $a->[0] or # 'ID' component.
$b->[3] <=> $a->[3] or # v-string part1.
$b->[4] <=> $a->[4] or # v-string part2.
$b->[5] <=> $a->[5] or # v-string part3.
$b->[1] <=> $a->[1] or # Numeric following 'ID'.
$b->[2] cmp $a->[2] # 'ABC' component.
} map {
[
m/^
(?:(\p{Alphabetic}+)(\d+)-)? # "ID", then digits.
(\p{Alphabetic}+)- # "ABC" component.
(\d+) # v-string part1.
(?:\.(\d+))? # v-string part2.
(?:\.?(\d+))? # v-string part3.
$/x,
$_
]
} @data;
};
say for @sorted;
And the output...
ID15-ABC-6.1
ID3-ABC-6.1
ID12-ABC-5.1.5
ID5-ABC-5.1.5
ID12-ABC-5.1
ID9-ABC-5.1
ID5-ABC-5.1
ABC-6.1
ABC-5.1.5
ABC-5.1
...which I think matches your specification.
To me this is a case where the Schwartzian Transform actually makes the code easier to follow. Imagine trying to do all the matching inline, within the sort routine. The biggest problem was trying to figure out how to format the code. lol
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.