# How can I check if two refs point to the same object?

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on

Hi,

I was wondering if there was a way I could check if two references
are referencing the same object.  For example, consider the following
code:

use Math::BigInt;
my \$n1 = Math::BigInt->new(5);
my \$n2 = \$n1;
my \$n3 = Math::BigInt->new(5);

In this code, \$n1, \$n2, and \$n3 will all be equivalent as far as the
'==' and 'eq' operators are concerned, but how can I check to see
which ones are referencing the same object?  In other words, how can I
tell that \$n1 and \$n2 are referring to the same object, and \$n3 is
not?

The only way I know how to do this is to run the following code:

use Data::Dumper;
print Dumper \$n1, \$n2, \$n3;

and check for lines like "\$VAR2 = \$VAR1;" but it seems like there
should be a more straight-forward way to do this.

Is there a way to see which references refer to the same object,
even when the '==' and 'eq' operators are overloaded?

Thanks,

-- Jean-Luc

## Re: How can I check if two refs point to the same object?

[...]

sub sameref
{
return defined(\$a1) && defined(\$a2) && \$a1 == \$a2;
}

use Math::BigInt;
my \$n1 = Math::BigInt->new(5);
my \$n2 = \$n1;
my \$n3 = Math::BigInt->new(5);

print "n1 sameref n2: ", (sameref(\$n1,\$n2) ? "yes" : "no"), "\n";
print "n1 sameref n3: ", (sameref(\$n1,\$n3) ? "yes" : "no"), "\n";
print "n2 sameref n3: ", (sameref(\$n2,\$n3) ? "yes" : "no"), "\n";

--
Alan Curry

## Re: How can I check if two refs point to the same object?

On Oct 11, 5:28=A0pm, pac...@kosh.dhis.org (Alan Curry) replied:

Thanks, Alan!  That's exactly what I'm looking for!

-- Jean-Luc