D
Domenico Discepola
Hello all. My goal is to be able to perform a "multi-field sort on a
multidimensional array". Having read many posts in the newsgroups, I was
unable to find a "straight" answer to this problem. I therefore came up
with this method. My question is, is there a more efficient solution to
this problem or is my method acceptable? Is there another CPAN module that
can be used? I welcome all opinions.
#!perl
use strict;
use warnings;
use Sort::Fields;
my ( @arr01, @arr02, $r, $c, $string, $aref, $delim, @arr_temp,
@arr_final );
@arr01 = ( [1, 'a', 'dom'],
[5, 'g', 'brad'],
[3, 'd', 'jamie'],
[7, 'd', 'abigail']);
$delim = "\t";
$string = "";
#Step 1 - combine fields into 1 string so that Sort::Fields will work
for $r ( 0 .. $#arr01 ) {
$aref = $arr01[$r];
for $c ( 0 .. $#{$aref} ) {
if ( $c == $#$aref ) {
$string = $string . $arr01[$r][$c];
} else {
$string = $string . $arr01[$r][$c]. $delim ;
}
}
push @arr02, $string;
$string = "";
}
#Step 2 - sort by field 2, then 3
my @sorted = fieldsort '\t', [2,3], @arr02;
#Step 3 - split sorted strings into mutidim array
foreach my $el ( @sorted ) {
@arr_temp = split $delim, $el;
push @arr_final, [@arr_temp];
}
#Step 4 - final output
print join('|', @$_), "\n" for @arr_final;
multidimensional array". Having read many posts in the newsgroups, I was
unable to find a "straight" answer to this problem. I therefore came up
with this method. My question is, is there a more efficient solution to
this problem or is my method acceptable? Is there another CPAN module that
can be used? I welcome all opinions.
#!perl
use strict;
use warnings;
use Sort::Fields;
my ( @arr01, @arr02, $r, $c, $string, $aref, $delim, @arr_temp,
@arr_final );
@arr01 = ( [1, 'a', 'dom'],
[5, 'g', 'brad'],
[3, 'd', 'jamie'],
[7, 'd', 'abigail']);
$delim = "\t";
$string = "";
#Step 1 - combine fields into 1 string so that Sort::Fields will work
for $r ( 0 .. $#arr01 ) {
$aref = $arr01[$r];
for $c ( 0 .. $#{$aref} ) {
if ( $c == $#$aref ) {
$string = $string . $arr01[$r][$c];
} else {
$string = $string . $arr01[$r][$c]. $delim ;
}
}
push @arr02, $string;
$string = "";
}
#Step 2 - sort by field 2, then 3
my @sorted = fieldsort '\t', [2,3], @arr02;
#Step 3 - split sorted strings into mutidim array
foreach my $el ( @sorted ) {
@arr_temp = split $delim, $el;
push @arr_final, [@arr_temp];
}
#Step 4 - final output
print join('|', @$_), "\n" for @arr_final;