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";
}
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).
References, by default, numify to their addresses. Those reference addresses are unique for every reference, so it can often be used in equality checks.
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.
Also, nothing guarantees references to numify to their address. Objects, for example, can use overloading to influence the value they return in different contexts.
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.