Reputation: 23501
I'm making a minimal case here, how should I dump the values of arrays inside array?
Multiple arrays, which contains a string value and a number, now I sort the array by second value, and read the value of the first field in order.
my @a = { "A" , 123 };
my @b = { "B" , 9 };
my @entries = ();
push @entries , \@a;
push @entries , \@b;
@entries = sort { $a[1] cmp $b[1] } @entries;
for (@entries)
{
print @_[0] , "\n"; // should be "A\nB" after for loop
}
And what document should I view? Hmm... it's not like normal array in array, e.g syntax like $a[0][0]
.
Upvotes: 0
Views: 122
Reputation: 206689
The first problem is that you don't have an array of arrays there, you end up having an array of arrays of hashes because of the {}
you use to construct @a
and @b
.
(BTW, a
and b
are poor choices as identifiers, especially given the use of scalar $a
and $b
in sort blocks – you don't want to confuse yourself with what you're dereferencing inside those sort blocks.)
If you fix that with:
my @a = ("A", 123);
my @b = ("B", 9);
Then you fix your sort to sort numerically (cmp
is a string sort, $a
and $b
are array references):
sort { $a->[1] <=> $b->[1] } @entries;
And then change your print
line to:
print $_->[0], "\n";
you should see the result you expect.
Add use strict; use warnings;
at the top of your script, and make liberal use of the Data::Dumper
module to debug it.
Upvotes: 4