perl:为什么Devel :: Refcount :: refcount和Devel :: Peek :: SvREFCNT不同意?

我正在阅读How can I access the ref count of a Perl hash?,并且建议使用Devel :: Refcount :: refcount和Devel :: Peek :: SvREFCNT.


这里有一个来自perldoc Devel的修改示例:Refcount:

use Devel::Peek;
use Devel::Refcount;

my $anon = [];

printf "Anon ARRAY $anon has %d/%d reference\n",

my $otherref = $anon;

printf "Anon ARRAY $anon now has %d/%d references\n",


Anon ARRAY ARRAY(0x8b10818) has 1/1 reference
Anon ARRAY ARRAY(0x8b10818) now has 2/1 references


(如果事实证明我没有做愚蠢的事情,我会添加从How can I access the ref count of a Perl hash?到这里的链接)

我不能说我已经把它全部了,但你的问题在Devel::Refcount perldoc年被突出显现


This function differs from Devel::Peek::SvREFCNT in that SvREFCNT() gives the reference count of the SV object itself that it is passed, whereas refcount() gives the count of the object being pointed to. This allows it to give the count of any referent (i.e. ARRAY, HASH, CODE, GLOB and Regexp types) as well.

Consider the following example program:

 use Devel::Peek qw( SvREFCNT );
 use Devel::Refcount qw( refcount );

 sub printcount
    my $name = shift;

    printf "%30s has SvREFCNT=%d, refcount=%d\n",
       $name, SvREFCNT($_[0]), refcount($_[0]);

 my $var = [];

 printcount 'Initially, $var', $var;

 my $othervar = $var;

 printcount 'Before CODE ref, $var', $var;
 printcount '$othervar', $othervar;

 my $code = sub { undef $var };

 printcount 'After CODE ref, $var', $var;
 printcount '$othervar', $othervar;

This produces the output

            Initially, $var has SvREFCNT=1, refcount=1
      Before CODE ref, $var has SvREFCNT=1, refcount=2
                  $othervar has SvREFCNT=1, refcount=2
       After CODE ref, $var has SvREFCNT=2, refcount=2
                  $othervar has SvREFCNT=1, refcount=2

Here, we see that SvREFCNT() counts the number of references to the SV object passed in as the scalar value – the $var or $othervar respectively, whereas refcount() counts the number of reference values that point to the referent object – the anonymous ARRAY in this case.

Before the CODE reference is constructed, both $var and $othervar have SvREFCNT() of 1, as they exist only in the current lexical pad. The anonymous ARRAY has a refcount() of 2, because both $var and $othervar store a reference to it.

After the CODE reference is constructed, the $var variable now has an SvREFCNT() of 2, because it also appears in the lexical pad for the new anonymous CODE block.

转载注明原文:perl:为什么Devel :: Refcount :: refcount和Devel :: Peek :: SvREFCNT不同意? - 代码日志