我使用存在,并且在规定的if语句所有的时间是否有Perl子程序存在和定义?
if (exists($a->{b}) and defined($a->{b})
是有没有在同一时间做这两个子程序?
更新:
似乎我没有给出很好的示例代码。对于更好的问题和匹配答案,请查看checking-for-existence-of-hash-key-creates-key。
我使用存在,并且在规定的if语句所有的时间是否有Perl子程序存在和定义?
if (exists($a->{b}) and defined($a->{b})
是有没有在同一时间做这两个子程序?
更新:
似乎我没有给出很好的示例代码。对于更好的问题和匹配答案,请查看checking-for-existence-of-hash-key-creates-key。
defined(...)
时exists(...)
是真实的,所以只能是真回答你问题是该子程序被称为defined
。
这是同样的事情
if (defined($a->{b}))
关于在评论中回复,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
->
另一方面,autovivifies为正常。
>perl -E"if (defined($a->{b})) { } say $a || 0;"
HASH(0x3fbd8c)
但这是exists
过的情况。
>perl -E"if (exists($a->{b}) and defined($a->{b})) { } say $a || 0;"
HASH(0x81bd7c)
如果你想避免自动激活,你会使用
>perl -E"if ($a && defined($a->{b})) { } say $a || 0;"
0
或
>perl -E"no autovivification; if (defined($a->{b})) { } say $a || 0;"
0
,如果你只是想检查的值关键存在(即使undef)然后只是使用存在()
这里是一个相关的问题,很好地解释它:What's the difference between exists and defined?
这是不对的。在最坏的情况下,当你使用' - >'操作符时,你无意中将'$ a'提升为散列引用。 – mob
应该指出,我最初的假设是错误的(定义不会产生一个关键)。 –
nit:'defined'是一个操作符,而不是一个子操作符。 – ikegami