为什么Perl的autovivification在这种情况下有效?

前端之家收集整理的这篇文章主要介绍了为什么Perl的autovivification在这种情况下有效?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有人可以帮助我理解这个Perl程序的输出

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

输出

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

“foo”来自哪里?怎么没有翻斗车打印出来?

请注意,如果我交换作业的顺序:

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

我的输出是我所期望的:

foo

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

编辑:
我知道使用严格;会抓住这个,但我更感兴趣的是知道如何打印字符串“foo”.

解决方法

你的代码丢失了

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.

确保所有脚本都以:

use strict;
use warnings;

鉴于:

$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}.

如果没有严格,你就不会发现脚本已遍及包名称空间.

添加一个

print Dumper \%main::;

要么

print Dumper \%main::foo;

运行此命令后检查符号表.

猜你在找的Perl相关文章