是否有Perl子程序存在并定义?

Eri*_*sum 0 perl operators subroutine

我使用exists并始终在if语句中定义

if (exists($a->{b}) and defined($a->{b})
Run Code Online (Sandbox Code Playgroud)

是否有一个子程序可以同时执行这两个操作?

更新:
似乎我没有提供非常好的示例代码.要获得更好的问题和匹配的答案,请查看hash-key-creates-key检查是否存在.

ike*_*ami 6

那是一样的

if (defined($a->{b}))
Run Code Online (Sandbox Code Playgroud)

关于注释中的回复,defined不实例化密钥.

>perl -E"if (exists($a->{b}) and defined($a->{b})) { }  say 0+keys(%$a);"
0

>perl -E"if (defined($a->{b})) { }  say 0+keys(%$a);"
0
Run Code Online (Sandbox Code Playgroud)

->另一方面,自动恢复正常.

>perl -E"if (defined($a->{b})) { }  say $a || 0;"
HASH(0x3fbd8c)
Run Code Online (Sandbox Code Playgroud)

但情况也是exists如此.

>perl -E"if (exists($a->{b}) and defined($a->{b})) { }  say $a || 0;"
HASH(0x81bd7c)
Run Code Online (Sandbox Code Playgroud)

如果你试图避免自动更新,你可以使用

>perl -E"if ($a && defined($a->{b})) { }  say $a || 0;"
0
Run Code Online (Sandbox Code Playgroud)

要么

>perl -E"no autovivification; if (defined($a->{b})) { }  say $a || 0;"
0
Run Code Online (Sandbox Code Playgroud)

  • @EricFossum您可能正在考虑自动生成,如果您在二维结构上使用`defined`,例如`defined $ foo - > {bar} {baz}`,它会创建子级`$ foo - > {吧}`但不是巴兹. (2认同)