Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re: Explaining Autovivication

by ikegami (Pope)
on Jun 12, 2008 at 08:41 UTC ( #691609=note: print w/replies, xml ) Need Help??

in reply to Explaining Autovivication

When a scalar ($foo, $foo[$i], $foo{$k}) is undefined and it is used as a reference (@$foo, $foo->[$i], ${$foo}[$i], %$foo, $foo->{$k}, ${$foo}{$k}, $$foo), two things can happen.

One possibility is that you get a warning. This occurs when you are trying to read from the dereferenced structure. (Technically, when the reference is used as an rvalue).

>perl -wle"my @x = @$ref; print $ref" Use of uninitialized value in array dereference at -e line 1. Use of uninitialized value in print at -e line 1.

The other possibility is that the reference is autovivified. That means the appropriate structure (array, hash or scalar) is constructed and a reference to it is stored in the variable. This occurs when you are trying to write to the dereferenced structure. (Technically, when the reference is used as an lvalue).

>perl -wle"@$ref = my @x; print $ref" ARRAY(0x225228)

Note then creating an alias to the dereferenced structure is an lvalue, and results in autovivification.

>perl -wle"sub {}->(@$ref); print $ref" ARRAY(0x225230) >perl -wle"for (@$ref) {} print $ref" ARRAY(0x225228)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://691609]
[ambrus]: Today I accidentally cut my hand while carrying a computer. On the display part of the motherboard that sticks out at the back of the chasis and has ports, there's this thin metal sheet with holes cut for the ports, to guide plugs into the sockets.
[ambrus]: This sheet has sharp needle-like parts, 0.004 long and less than 0.001 wide, that can get bent to point outwards, and one of these cut into my palm when I lifted the box.
[ambrus]: So now when I choose what motherboard to buy for my new home computer, I have one more specific property to guide me. Useful, because there's so many different boards to choose from.

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (10)
As of 2017-01-16 19:36 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (151 votes). Check out past polls.