我应该如何比较Perl参考? [英] How should I compare Perl references?

查看:117
本文介绍了我应该如何比较Perl参考?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查两个引用是否指向同一个对象。看来我可以简单地使用

I want to check if two references point to the same object. It seems I can simply use

if ($ref1 == $ref2) { 
 # cheap numeric compare of references
 print "refs 1 and 2 refer to the same thing\n";
}



< org / perlref.html> perlref ,但我模糊地记得看到某些函数的使用是为了相同的目的。是否有任何原因我不应该使用简单的数值等价测试?

as mentioned in perlref, but I vaguely remember seeing the use of some function for the same purpose. Is there any reason I shouldn't use the simple numerical equality test?

注意我只想知道引用是否指向完全相同的对象。

Note I only want to know whether the references point to the exact same object. I don't look for a way to compare the content of the object(s).

推荐答案

默认情况下,引用numify到他们的地址。这些引用地址对于每个引用是唯一的,因此它通常可以用于相等性检查。

References, by default, numify to their addresses. Those reference addresses are unique for every reference, so it can often be used in equality checks.

但是,在您显示的代码段中,您首先必须确保 $ ref1 $ ref2 实际上是引用。否则,由于包含引用地址的常规标量,您可能会得到不正确的结果。

However, in the snippet you showed, you'd first have to make sure that both $ref1 and $ref2 are actually references. Otherwise you might get incorrect results due to regular scalars containing reference addresses.

此外,没有任何保证引用numify到它们的地址。例如,对象可以使用重载来影响它们在不同上下文中返回的值。

Also, nothing guarantees references to numify to their address. Objects, for example, can use overloading to influence the value they return in different contexts.

比直接比较引用数字相等的更坚实的方法是使用 refaddr 的功能由 Scalar :: Util ,确保两边都是引用。

A more solid way than comparing references directly for numeric equality would be to use the refaddr function as provided by Scalar::Util, after making sure both sides actually are references.

这篇关于我应该如何比较Perl参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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