Evgeny
Evgeny

Reputation: 2161

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

Upvotes: 2

Views: 2023

Answers (2)

ikegami
ikegami

Reputation: 385779

$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'} = [];

Upvotes: 8

Sobrique
Sobrique

Reputation: 53478

Data::Dumper will tell you the problem here:

use strict;
use warnings;
use Data::Dumper;
my %x;
push @{$x{'12'}}, ();

print Dumper \%x;

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

print Dumper \%y;

Gives:

$VAR1 = {
          '12' => []
        };
$VAR1 = {
          '12' => undef
        };

The two commands aren't equivalent.

Maybe you want:

$y{'12'} = [];

Instead - [] denotes an anonymous array, where () denotes an empty list of elements.

Upvotes: 8

Related Questions