So, for example i have array like that:
my @arr = (
"blabla\t23\t55",
"jkdcbx\t55\t89",
"jdxjcl\t88\t69",
......)
And i need to sort this array by second column after \t, without outer splits. Is it possible to do?
So, for example i have array like that:
my @arr = (
"blabla\t23\t55",
"jkdcbx\t55\t89",
"jdxjcl\t88\t69",
......)
And i need to sort this array by second column after \t, without outer splits. Is it possible to do?
May be a more elegant way but this will work :
my @arr = ( "blabla\t23\t55", "jkdcbx\t55\t89", "jdxjcl\t88\t69");
for (sort {(split(/\t/,$a))[2] <=> (split(/\t/,$b))[2]} @arr) {
print "$_\n";
}
my %arr_assoc; my @arr = ( "blabla\t23\t55", "jkdcbx\t55\t89", "jdxjcl\t88\t69"); for (@arr) {$a = (split(/\t/))[2]; $arr_assoc{$_}=$a} for (sort {$arr_assoc{$a} <=> $arr_assoc{$b}} keys %arr_assoc) {print "$_\n"}I've just realised that your question may mean that you want to sort by the third column instead of the second
That would be done by using
my ($aa, $bb) = map { (split /\t/)[2] } $a, $b;
instead
blabla 23 55
jdxjcl 88 69
jkdcbx 55 89
I always prefer to use map to convert the values from the original data into the function that they should be sorted by
This program demonstrates
I assume you want the values sorted numerically? Unfortunately your example data is already sorted as you describe
use strict;
use warnings 'all';
use feature 'say';
my @arr = (
"blabla\t23\t55",
"jkdcbx\t55\t89",
"jdxjcl\t88\t69",
);
my @sorted = sort {
my ($aa, $bb) = map { (split /\t/)[1] } $a, $b;
$aa <=> $bb;
} @arr;
say for @sorted;
blabla 23 55
jkdcbx 55 89
jdxjcl 88 69
Try this
use warnings;
use strict;
no warnings "numeric";
my @arr = (
"blabla\t23\t55",
"jkdcbx\t85\t89",
"jdxjcl\t83\t69",
);
my @result = sort {$a=~s/^[^\t]*\t//r <=> $b=~s/^[^\t]*\t//r } @arr;
$, = "\n";
print @result,"\n";
I have used following technique with sort for to do it
Non-destructive modifier(-r) - perform non-destructive substitution and return the new value
And tured of the warning for numeric