I have a perl array of strings like this:
my @arr = ( "gene1 (100)", "gene2 (50)", "gene3 (120)", ... );
How can I sort the array by the integer in parentheses?
Using a transform to compare the first number in the string
use strict;
use warnings;
my @arr = ( "gene1 (100)", "gene2 (50)", "gene3 (120)");
my @sorted = map {$_->[0]}
sort {$a->[1] <=> $b->[1]}
map {[$_, /\b(\d+)\b/]} @arr;
print "$_\n" for @sorted;
Outputs:
gene2 (50)
gene1 (100)
gene3 (120)
The sort built-in in Perl lets you pass a code reference as its first argument to define how the sort should be done. Inside this code ref, you can use any function you want.
Since you want to do it with a regular expression, it makes sense to create a sub that matches the numbers in the parenthesis and use that in your sorting function.
You need to call it once for $a and $b, the two variables that will be compared to each other for each round of sorting pairs. You should use the <=> operator, which is used for sorting numbers in ascending order.
This is a very verbose version.
use strict;
use warnings;
use Data::Dump;
my @arr = ( "gene1 (100)", "gene2 (50)", "gene3 (120)", );
dd sort { get_number($a) <=> get_number($b) } @arr;
sub get_number {
my ( $string ) = @_;
return $1 if $string =~ m/\((\d+)\)/;
return 0; # assume it goes last if there is no number
}
Output:
("gene2 (50)", "gene1 (100)", "gene3 (120)")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With