I have an array of strings. Each string has multiple fields delimited by a pipe character. I want to do a reverse numerical sort of the strings by the first field in each string. I've written some perl code that works fine and I'm wondering if there is a more perlish way to write this.
sub by_firstField {
my @tmpA = split ( /\|/, $a ) ;
my @tmpB = split ( /\|/, $b ) ;
if ($tmpA[0]> $tmpB[0]) { -1 } elsif ($tmpA[0] < $tmpB[0]) { 1 } else { 0 }
}
push @unsorted, ( "8.02|a|b|c", "47.6|d|e|f", "108.1|g|h|i", "411.5|j|k|l", "8.1|m|n|o" ) ;
@sorted = sort by_firstField @unsorted ;
for ( my $i = 0 ; $i <= $#sorted; $i++ ) {
print $sorted[$i] . "\n" ;
}
411.5|j|k|l
108.1|g|h|i
47.6|d|e|f
8.1|m|n|o
8.02|a|b|c
sort {
my @fields_a = split /\|/, $a;
my @fields_b = split /\|/, $b;
$fields_b[0] <=> $fields_a[0]
}
or
sort { ( $b =~ /([^|]*)/ )[0] <=> ( $a =~ /([^|]*)/ )[0] }
or
map $_->[0],
sort { $b->[1] <=> $a->[1] }
map [ $_, split /\|/ ],