http://qs321.pair.com?node_id=1070214


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.