3

有人能帮我理解这个 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'
        };

“富”从何而来?怎么不是dumper打印出来的?

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

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'
        };

编辑:我知道这use strict;会抓住这一点,但我更感兴趣的是知道字符串“foo”是如何被打印的。

4

4 回答 4

17

您的代码丢失

use strict;
C:\Temp> 回
不能使用字符串(“foo”)作为哈希引用,而“严格引用”在使用
C:\Temp\hui.pl 第 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}

如果没有strict,您将不会发现脚本已经践踏了整个包名称空间。

添加一个

print Dumper \%main::;

或者

print Dumper \%main::foo;

运行后检查符号表。

于 2009-11-18T22:12:33.497 回答
2

基本上字符串 "foo" 是 的唯一值%hash,但是(由于非严格性)正在创建 %foo ,其中包含(world => "bar")

于 2009-11-18T22:26:16.320 回答
1

如果您使用严格,您的脚本会出错。

不能将字符串 ("foo") 用作 HASH 引用,而 "strict refs" 在 ...

于 2009-11-18T22:14:38.743 回答
1

仅当您以未定义的值开始时,自动激活才有效。由于您$hash{hello}不是未定义的值,因此您不会自动激活下一个级别。相反,您最终将$hash{hello}其用作软参考。

于 2009-11-19T20:59:33.333 回答