Alex Artukh Alex Artukh - 5 months ago 11
Perl Question

Custom sorting for an array of strings

I have a text file with several lines

abc 122 aaaaaaa
cba 165 aaaaaaaa
aaa 123 aaaaaaaaa
bvc 443 aaaaaaaaaa
rdc 993 aaaaaaaaaaa
qwe 103 aaaaaaaaaaaa


Each line contains a decimal number.
Can I sort this lines using decimal number as a marker for a sorting?

I want to do something like this but this code is not working.

for my $line (sort @lines {(($a =~ /(\d+)/)[0]) <=> (($b =~ /(\d+)/)[0])}) {
print $line;
}

Answer

Try this.

Store the grouping elements in a temporary variable and perform sort from that variable.

use warnings;
use strict;
my @ar = <DATA>;
my $m;
my $n;
foreach (sort{ ($m)=$a=~/(\d+)/; ($n)=$b=~/(\d+)/; $m <=>$n } @ar)
{
    print "$_";

}


__DATA__
abc 122 aaaaaaa
cba 165 aaaaaaaa
aaa 123 aaaaaaaaa
bvc 443 aaaaaaaaaa
rdc 993 aaaaaaaaaaa
qwe 103 aaaaaaaaaaaa
Comments