Why does Perl autovivitation work in this case?

Can someone help me understand the output of this Perl program:

use Data::Dumper;
my %hash;
$hash{hello} = "foo";
$hash{hello}{world} = "bar";
print $hash{hello} . "\n";
print $hash{hello}{world} . "\n";
print Dumper(\%hash);

And the conclusion:

foo
bar
$VAR1 = {
          'hello' => 'foo'
        };

Where does "foo" come from? Why is it not printed out with a dump truck?

Please note that if I change the order of assignments:

use Data::Dumper;
my %hash;
$hash{hello}{world} = "bar";
$hash{hello} = "foo";
print $hash{hello} . "\n";
print $hash{hello}{world} . "\n";
print Dumper(\%hash);

My conclusion is what I expect:

foo

$VAR1 = {
          'hello' => 'foo'
        };

EDIT: I know I use strict;will catch this, but I'm more interested in knowing how the string "foo" is still printed.

+3
source share
4 answers

Your code is missing

use strict;
C: \ Temp> hui
Can't use string ("foo") as a HASH ref while "strict refs" in use at 
C: \ Temp \ hui.pl line 7.

Make sure all your scripts start with:

use strict;
use warnings;

Given:

$hash{hello} = "foo";

$hash{hello} -.

$hash{hello}{world} = "bar";

"foo" - %main::foo $foo{world} "bar".

:

print Dumper \%hash;

%hash.

print $hash{hello}{world} . "\n";

$foo{world}.

strict , script .

print Dumper \%main::;

print Dumper \%main::foo;

.

+17

"foo" %hash, (- ) % foo, (world => "bar")

+2

, script.

string ( "foo" ) HASH ref " "...

+1

Autovivitation only works when you start with undefined values. Since yours is $hash{hello}not an undefined value, you should not auto-generate the next level. Instead, you use it $hash{hello}as a soft link.

+1
source

Source: https://habr.com/ru/post/1723283/


All Articles