为什么 Perl 的自动激活在这种情况下起作用?
有人可以帮助我理解这个 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”来自哪里?怎么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”仍然被打印。
Can some one 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 output:
foo
bar
$VAR1 = {
'hello' => 'foo'
};
Where is the "foo" coming from? How come it isn't printed out by dumper?
Note that if I swap the order of the 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 output is what I expect:
foo
$VAR1 = {
'hello' => 'foo'
};
EDIT:
I know that use strict;
would catch this, but I'm more interested in know how the string "foo" is still being printed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的代码丢失
确保所有脚本都以以下内容开头:
鉴于:
$hash{hello}
是不是哈希引用。将字符串
"foo"
视为哈希引用并创建哈希%main::foo
并将$foo{world}
设置为“栏”
。当您这样做时:
它只打印
%hash
的内容。然而,当你这样做时,它会打印
$foo{world}
。如果没有
strict
,您就不会发现脚本已经破坏了整个包名称空间。添加一个
或来检查符号表。
运行后
Your code is missing
Make sure all your scripts start with:
Given:
$hash{hello}
is NOT a hash reference.treats the string
"foo"
as a hash reference and creates the hash%main::foo
and sets$foo{world}
to"bar"
.When you do:
it only prints the contents of
%hash
. Whereas, when you doit prints
$foo{world}
.Without
strict
, you do not get to find out that the script has trampled all over the package name space.Add a
or
to inspect the symbol table after you run this.
基本上,字符串“foo”是
%hash
的唯一值,但是(由于非严格性)正在创建包含(world => "bar")
Basically the string "foo" is the only value of
%hash
, but (due to non-strictyness) %foo is being created that contains(world => "bar")
如果您使用严格,您的脚本将会出错。
If you were using strict, you'd get an error with your script.
仅当您以未定义的值开始时,自动生存才起作用。由于您的
$hash{hello}
不是未定义的值,因此您不会自动激活下一个级别。相反,您最终使用$hash{hello}
作为软引用。Autovivification only works when the you start with undefined values. Since your
$hash{hello}
isn't an undefined value, you don't autovivify the next level. Instead, you end up using$hash{hello}
as a soft reference.