Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Wrong dereference => Out of memory

by Anonymous Monk
on Oct 29, 2012 at 15:10 UTC ( [id://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.

Replies are listed 'Best First'.
Re^2: Wrong dereference => Out of memory
by tobyink (Canon) 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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2024-04-19 05:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found