Search code examples
perldata-structuresperl-data-structures

Adding an empty array to hash


What is the difference between:

my %x;
push @{$x{'12'}}, ();

and:

my %y;
$y{'12'} = ();

Why does the following work for x and not for y?

my @x1 = @{$x{'12'}}; #legal
my @y1 = @{$y{'12'}}; #illegal

Solution

  • $y{'12'} = ();
    

    and

    @{$y{'12'}} = ();
    

    are not the same. In the first case, you are assigning to a hash element. In the second case, you are assigning to the array referenced by that hash element.

    Except it doesn't contain a reference to an array, so Perl creates one for you through a feature called "autovivification". In other words,

    @{$y{'12'}} = ();
    

    is equivalent to

    @{ $y{'12'} //= [] } = ();
    

    where [] creates an array and returns a reference to it. Given that $y{'12'} is non-existent and thus undefined, the above simplifies to the following:

    $y{'12'} = [];