Perl sort 2d array with links

I'm a little new to perl, so please bear with me. I have exhausted all possible solutions that I could find so far.

Say I have hats with some dimensions that are filled elsewhere. And I want to sort them based on a specific column. I am trying to do this using perl "sort", but I do not understand how they are sorted. I believe the problem is that I got confused in the links. The code below is what I'm working with right now.

my @hat1 = [3, 4, 5, 6, 7, 8];
my @hat2 = [4, 6, 5, 1, 1, 2];
my @hat3 = [9, 8, 9, 3, 4, 4];
#eventually work with unknown number of hats

my @binToSort = (\@hat1,\@hat2,\@hat3);

my @binSorted = sort { $a->[4] <=> $b->[4] } @binToSort;

for my $ref (@binSorted){
    for my $inner (@$ref){
        print "@$inner\n";
    }
}

At the moment, it is printing the values ​​of an unsorted array:

3 4 5 6 7 8
4 6 5 1 1 2
9 8 9 3 4 4

But I want to be able to:

4 6 5 1 1 2
9 8 9 3 4 4
3 4 5 6 7 8

I feel this is a simple problem, but I cannot figure out how to do this. Any help is much appreciated!

+4
source share
1 answer

You need:

my $hat1 = [ 3, 4, 5, 6, 7, 8 ];
my $hat2 = [ 4, 6, 5, 1, 1, 2 ];
my $hat3 = [ 9, 8, 9, 3, 4, 4 ];

#eventually work with unknown number of hats

my @binToSort = ( $hat1, $hat2, $hat3 );

my @binSorted = sort { $a->[4] <=> $b->[4] } @binToSort;

for my $ref (@binSorted) {
    for my $inner ( @{$ref} ) {
        print "$inner";
    }
    print "\n";
}

or

my @hat1 = ( 3, 4, 5, 6, 7, 8 );
my @hat2 = ( 4, 6, 5, 1, 1, 2 );
my @hat3 = ( 9, 8, 9, 3, 4, 4 );

#eventually work with unknown number of hats

my @binToSort = ( \@hat1, \@hat2, \@hat3 );

my @binSorted = sort { $a->[4] <=> $b->[4] } @binToSort;

for my $ref (@binSorted) {
    for my $inner ( @{$ref} ) {
        print "$inner";
    }
    print "\n";
}
+3
source

All Articles