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

J

jl_post

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
 
A

Alan Curry

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); [...]

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

Get their addresses with Scalar::Util::refaddr and compare.

use Scalar::Util 'refaddr';

sub sameref
{
my ($a1,$a2) = (refaddr($_[0]), refaddr($_[1]));
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";
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top