Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: The number of references to a variable

by lima1 (Curate)
on Nov 26, 2007 at 12:29 UTC ( #652972=note: print w/replies, xml ) Need Help??


in reply to The number of references to a variable

The SvREFCNT macro (perlguts) returns this number. I am sure this is already somewhere on cpan, but a simple XS routine could look like this:
/* generated by h2xs -c Scalar::RefCount */ #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "ppport.h" MODULE = Scalar::RefCount PACKAGE = Scalar::RefCount int refcount(s) SV* s PROTOTYPE: $ CODE: RETVAL = SvREFCNT(s); OUTPUT: RETVAL
use Test::More tests => 6; BEGIN { use_ok('Scalar::RefCount') }; ######################### my $a; is(Scalar::RefCount::refcount($a),1, 'return 1'); my $b = \$a; is(Scalar::RefCount::refcount($a),2, 'return 2'); my $c = \$a; is(Scalar::RefCount::refcount($a),3, 'return 3'); { my $d = \$a; is(Scalar::RefCount::refcount($a),4, 'return 4'); } is(Scalar::RefCount::refcount($a),3, 'return 3');
Update: Ah, thanks cdarke.

Replies are listed 'Best First'.
Re^2: The number of references to a variable
by cdarke (Prior) on Nov 26, 2007 at 13:12 UTC
    SvREFCNT is exposed in Devel::Peek (no need to go to CPAN), which is a bit easier to use than embedding XS. For example:
    use Devel::Peek qw(SvREFCNT); $x = 42; $y = \$x; $refs_for_x = SvREFCNT($x); print "$refs_for_x\n";
    Prints 2.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://652972]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2021-04-15 10:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?