Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

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)


Comment on Re: Explaining Autovivication
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2015-08-01 00:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (285 votes), past polls