Reputation: 43
I am somewhat new to perl so please bear with me. I've exhausted all possible solutions I could find so far.
Let's say I have some hats with some measurements that are filled elsewhere. And I want to sort them based on a certain column. I try to do this using perl's "sort" but I don't get them to actually sort. I believe the problem is that I'm confused on references. The code below is what I'm working with at the moment.
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";
}
}
As of now it prints out the unsorted array values:
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 arrive at:
4 6 5 1 1 2
9 8 9 3 4 4
3 4 5 6 7 8
I feel like this is a simple problem but I can't figure out the right way to do it. Any help is much appreciated!
Upvotes: 4
Views: 166
Reputation: 10666
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";
}
Upvotes: 3