Demetri Demetri - 5 months ago 8x
Perl Question

How can I check for reference equality in Perl?

In Perl, how can I check for pointer equality of two different mutable objects?

Since almost everything is mutable in Perl, there might be times when it is desirable to know when two objects are identical – that is, modifying one will effect the other. How can one do that?

Edit: By "object" I mean any Perl value. This includes strings, arrays, hashes, etc.


If you know both values are references, you can use the numeric equality operator == to compare them.

If you aren't sure that both values are references, you can test them with ref first.

if(ref($x) && ref($y) && $x==$y) {
  print "\$x and \$y are references to the same thing.\n"

This is documented in perlref, which says

Using a string or number as a reference produces a symbolic reference, as explained above. Using a reference as a number produces an integer representing its storage location in memory. The only useful thing to be done with this is to compare two references numerically to see whether they refer to the same location.