0

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].

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

And $a[1] cmp $b[1] should be $a->[1] <=> $b->[1]
@a and @b doesn't interfere with sort, as you can see in this very case.
@ikegami: thanks, had fixed that in my test but forgot about it :) As for @a, indeed it's not a problem here, but best avoid them anyway (in my opinion).
They're best to avoid because they're generally poor names. Not for any non-existing relationship with sort. That's silly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.