in reply to Sort multi-dimensional array based on dereferenced value - out of memory error

The problem is that $a and $b inside the sort block are array references (and not indexes to them), and you use them as indexes, so as numbers.

When you use a reference as a number, it evaluates to the memory address of the referencee. This address can be a rather large number, and your code autovivifies an array big enough to hold that many elements.

$ perl -wE 'say 0 + []' 10034664

So it tries to create an array with about 10Mio elements on my machine.

The fix is to use just $a in place of $aref->[$a] in your code

Replies are listed 'Best First'.
Re^2: Sort multi-dimensional array based on dereferenced value - out of memory error
by lbmp (Initiate) on Sep 05, 2011 at 15:32 UTC

    Aha! Thanks to both of you (Anonymous Monk and moritz) for the clear explanation. Indeed, it works fine when not using $a and $b as indexes.

    Additionally, I noticed that when running with -w, perl tells me exactly what I was doing wrong:

    $ perl -w foo.pl
    Use of reference "ARRAY(0x8153c28)" as array index at foo.pl line 21.
    Out of memory!
    

    Lesson learned!