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

前端之家收集整理的这篇文章主要介绍了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",Devel::Refcount::refcount($anon),Devel::Peek::SvREFCNT($anon);

my $otherref = $anon;

printf "Anon ARRAY $anon now has %d/%d references\n",Devel::Peek::SvREFCNT($anon);

其中打印出来:

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

注意最后的2/1差异…

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

解决方法

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

COMPARISON WITH SvREFCNT

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;
 printcount '$othervar',$othervar;

 my $code = sub { undef $var };

 printcount 'After CODE ref,$othervar;

This produces the output

Initially,$var has SvREFCNT=1,refcount=1
      Before CODE ref,refcount=2
                  $othervar has SvREFCNT=1,refcount=2
       After CODE ref,$var has SvREFCNT=2,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相关文章