存在和定义之间有什么区别? [英] What's the difference between exists and defined?

查看:208
本文介绍了存在和定义之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两者之间有什么区别

if (defined $hash{$key}) { }

if (exists $hash{$key}) { }

我什么时候知道该使用哪个?

When do I know which to use?

推荐答案

这在 defined exists .快速摘要:

This is well-documented in the perldoc entries for defined and exists. Here's a quick summary:

defined $hash{key}告诉您是否已定义给定键的值(即未定义undef).用它来区分未定义的值和在布尔上下文(例如0'')中为假的值.

defined $hash{key} tells you whether or not the value for the given key is defined (i.e. not undef). Use it to distinguish between undefined values and values that are false in a boolean context such as 0 and ''.

exists $hash{key}告诉您%hash是否包含给定密钥.用它来区分未定义的值和不存在的值.

exists $hash{key} tells you whether or not %hash contains the given key. Use it to distinguish between undefined values and non-existent ones.

使用示例最容易看出这一点.给定此哈希值:

This is easiest to see with an example. Given this hash:

my %hash = (a => 1, b => 0, c => undef);

以下是检索,定义性和存在的结果:

Here are the results for retrieval, defined-ness, and existence:

# key  value  defined  exists
a          1        1       1
b          0        1       1
c      undef        0       1
d      undef        0       0

实际上,人们常常只写if ($hash{key}) {...},因为(在许多常见情况下)只有真正的值才有意义/可能.如果错误值有效,则必须 defined()添加到测试中. exists()的使用频率要低得多.最常见的情况是使用哈希作为集合时.例如

In practice, people often write just if ($hash{key}) {...} because (in many common cases) only true values are meaningful/possible. If false values are valid you must add defined() to the test. exists() is used much less often. The most common case is probably when using a hash as a set. e.g.

my %set = map { $_ => undef } 'a' .. 'z';

使用undef作为设置值具有以下优点:

Using undef for set values has a few advantages:

  1. 它更准确地表示了意图(仅键是有意义的,而不是值).
  2. 所有undef值共享一个分配(节省内存).
  3. exists()测试要快一些(因为Perl不必检索该值,只需确定存在一个即可).
  1. It more accurately represents the intent (only the keys are meaningful, not the values).
  2. All undef values share a single allocation (which saves memory).
  3. exists() tests are slightly faster (because Perl doesn't have to retrieve the value, only determine that there is one).

它的另一个缺点是,您必须使用exists()来检查集合成员身份,这需要更多的键入操作,并且如果忘记了它会做错事.

It also has the disadvantage that you have to use exists() to check for set membership, which requires more typing and will do the wrong thing if you forget it.

exists有用的另一个地方是在尝试检索值之前探测锁定的哈希值(这将触发异常).

Another place where exists is useful is to probe locked hashes before attempting to retrieve a value (which would trigger an exception).

这篇关于存在和定义之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆