Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: Wrong dereference => Out of memory

by Anonymous Monk
on Oct 29, 2012 at 15:10 UTC ( #1001375=note: print w/ replies, xml ) Need Help??

in reply to Wrong dereference => Out of memory

First of all, this is about pseudo-hashes. This (now long gone) feature lets you access an array reference as if it was a hash reference.

So what does $aref->{key} actually do? Well, this: $aref->[$aref->[0]{key}]. That is, it fetches the first element of the array (which must be a hashref) and uses it to map the key to an array index, which is then finally looked up in @$aref.

The other piece of the puzzle is autovivification (also explained in perldoc perlref). This is what automatically creates references for you when you try to dereference something that doesn't exist. Example:

my $foo; $foo->[1] = 42; # automatically sets $foo = [] before the # assignment so you end up with $foo = [undef, 42] instead of # dying with "Can't use undef as an ARRAY reference"

OK, now let's look at your code again. $a->{test} looks up "test" in { test => { val => 1 }} (the first element of @$a) and returns { val => 1 }. It then uses this reference as an array index, which converts it to a (very large) integer (the internal memory address of the hash).

$a->[0xDEADBEEF] obviously doesn't exist; the array only has two elements. But since you're dereferencing it (the ->{val} part), perl tries to autovivify a hashref for you. Unfortunately this involves resizing the array to have 0xDEADBEEF + 1 elements (the intervening elements are set to undef). At this point perl is running out of memory, as expected.

Comment on Re: Wrong dereference => Out of memory
Select or Download Code
Re^2: Wrong dereference => Out of memory
by tobyink (Abbot) on Oct 29, 2012 at 15:28 UTC

    Meh. By the time I've figured it out, somebody else has already posted a perfect explanation!

    I'd ++ you if you weren't an anonymous monk.

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re^2: Wrong dereference => Out of memory
by schetchik (Beadle) on Oct 29, 2012 at 15:41 UTC
    Thank you very much.

    I agree, it's a great explanation.

    Sorry, i can't put more then one plus for you message :)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1001375]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (9)
As of 2014-07-30 03:45 GMT
Find Nodes?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:

    Results (229 votes), past polls