Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Autovivification in perl

by pemungkah (Priest)
on Jan 11, 2014 at 00:17 UTC ( #1070214=note: print w/replies, xml ) Need Help??


in reply to Autovivification in perl

"Autivivification" is a fancy word for "don't let me mess up if stuff isn't there yet".

In hashes, autovivification creates the hash entry you were looking for and sets it to undef; if you try to continue down a chain of references to other anonymous data structures, autovivification creates them (empty) and continues.

So If you said

$pinky = {}; $pinky->{zorch}{poit}{narf} = "I don't know, Brain, where will we get +hip-waders this time of night?";
what logically happens is this:
$pinky = {}; # Ooh, you referenced zorch, and it's not there. $pinky->{zorch} = undef; # And now you want to reference 'poit' in that as a hash, so we'll add + an new anonymous hash instead: $pinky->{zorch} = {}; $pinky->{zorch}{poit} = undef; # and then you want to go one more level: $pinky->{zorch}{poit} = {}; $pinky->{zorch}{poit}{narf} = undef; # And you want to set that to a value: $pinky->{zorch}{poit}{narf} = "I don't know, Brain, where will we get +hip-waders this time of night?";
Note that Perl does not actually keep doing and undoing the assignments of undef; it just plows through, building the structures as it goes. That's autovivification. Note that if you just access something at the end of one of these chains, you'll get undef; Perl does set the value to undef if you don't assign it anything, just as it would if you referenced a key in a hash that hadn't been set yet.

Also note that this

$eat_memory={}; $eat_memory->{bad_idea}[99999][99999][99999] = "yummy, yummy, memory";
forces autovivification to create all those unused entries in the arrays, so we have 'bad_idea' referencing a 100,000 element anonymous array, the last element of which references a 100,000 element anonymous array, the last element of which references another 100,000 element array, the last element of which is set to our string. Using hashes unless you absolutely have to use arrays will let you simulate a sparse array.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (1)
As of 2022-05-20 23:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (76 votes). Check out past polls.

    Notices?