Search code examples
perlautovivification

Perl Hashref initialize and assign at once


Actually I found a weird behavior when i try to initialize a Perl Hash(ref) and try to assign it via autovivication at once. Here is a short Codesnippet to make it a bit clearer:

use Data::Dumper;
my $hash->{$_} = 'abc' foreach (1..4);
print Dumper $hash;

That prints:

$VAR1 = undef;

When i try it that way:

use Data::Dumper;
my $hash;
$hash->{$_} = 'abc' foreach (1..4);
print Dumper $hash;

i get

$VAR1 = {
          '4' => 'abc',
          '1' => 'abc',
          '3' => 'abc',
          '2' => 'abc'
        };

Which is what i expected. So the Problem is the (multiple) initialzing of $hash.

I know, that the way of using map is a better solution here:

use Data::Dumper;
my $hash = { map { $_ => 'abc' } (1..4) };
print Dumper $hash;

Now my Question: Why does the way of initialzing and assigning at once fail?


Solution

  • Read the note near the end of the Statement Modifiers section of the perlsyn - Perl Syntax:

    NOTE: The behaviour of a my, state, or our modified with a statement modifier conditional or loop construct (for example, my $x if ... ) is undefined. The value of the my variable may be undef, any previously assigned value, or possibly anything else. Don't rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons.