加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 06:11:01 所属栏目:大数据 来源:网络整理
导读:有人可以帮助我理解这个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); 并输出: foobar$VAR1 = { 'hello' = 'foo' };
有人可以帮助我理解这个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:Temphui.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;

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读