Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Analysis of a Perl autovivification example

Consider this one piece of Perl code,

$array[$x]->{“foo”}->[0] = “January”;

I analyze this code as following: The entry with index $x in the @array is a hashref. With respect to this hash, when its key is foo, its value is an array and the 0-th element for this array is January. Is my analysis correct or not?

like image 249
bit-question Avatar asked Nov 26 '25 11:11

bit-question


2 Answers

Your analysis of the structure is correct, however the related autovivification example would be something more like:

#!/usr/bin/env perl

use strict;
use warnings;

use 5.10.0; # say

my @array;

# check all levels are undef in structure

say defined $array[0] ? 'yes' : 'no';         # no
say defined $array[0]{foo} ? 'yes' : 'no';    # no
say defined $array[0]{foo}[0] ? 'yes' : 'no'; # no

# then check again

say defined $array[0] ? 'yes' : 'no';         # yes (!)
say defined $array[0]{foo} ? 'yes' : 'no';    # yes (!)
say defined $array[0]{foo}[0] ? 'yes' : 'no'; # no

Notice that you haven't assigned anything, in fact all you have done is to check whether something exists. Autovivification happens when you check a multilevel data structure at some level x, then suddenly all levels lower (x-1 ... 0) are suddenly existent.

This means that

say defined $array[0]{foo}[0] ? 'yes' : 'no';

is effectively equivalent to

$array[0] = {};
$array[0]{foo} = [];
say defined $array[0]{foo}[0] ? 'yes' : 'no';
like image 160
Joel Berger Avatar answered Nov 28 '25 16:11

Joel Berger


Yes, your analysis is correct.

It is NOT however, an analysis of autovivification, it is an analysis of a multilevel data structure.

We cannot know if there is autoviv going on here or not, because we cannot determine whether any of the intermediate values are undef.

like image 21
tadmc Avatar answered Nov 28 '25 16:11

tadmc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!