Reputation: 249
I'm new to Perl and stuck with an array sorting problem.
For example if my input is
@lines = qw/ S-1.1 A-1.4 V-1.3 /
output should be in the order
A-1.4, V-1.3, S-1.1.
The idea is sort out based on what comes after -
in the string. I tried sort {$a <=> $b} @lines
but it did not help.
Please advise some idea to get this done.
Upvotes: 2
Views: 187
Reputation: 1921
use strict;
use warnings;
my @lines = ("S-1.1", "A-1.4", "V-1.3");
@lines = sort { (split /-/, $b)[1] <=> (split /-/, $a)[1] } @lines;
print join ', ', @lines;
output
A-1.4, V-1.3, S-1.1
Upvotes: 3
Reputation: 87421
my @lines = qw(S-1.1 A-1.4 V-1.3);
@lines = sort { substr($a, index($a, '-') + 1) <=>
substr($b, index($b, '-') + 1) } @lines;
print "@lines\n"; #: S-1.1 V-1.3 A-1.4
If you want to have more than one dot in the strings, it becomes a bit more complicated:
sub pad($) {
local $_ = $_[0];
s/^[^-]*?-//;
s/(\d+)/sprintf("%020d",$1)/ge;
$_
}
my @lines = qw(S-1.2.12 B-1.2.9 A-1.4 V-1.3);
@lines = sort { pad($a) cmp pad($b) } @lines;
print "@lines\n"; #: B-1.2.9 S-1.2.12 V-1.3 A-1.4
Upvotes: 1