加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl:为什么Devel :: Refcount :: refcount和Devel :: Peek ::

发布时间:2020-12-15 21:33:30 所属栏目:大数据 来源:网络整理
导读:我正在阅读 How can I access the ref count of a Perl hash?,并且建议使用Devel :: Refcount :: refcount和Devel :: Peek :: SvREFCNT. 但是他们没有返回相同的引用计数.这是为什么? 这里有一个来自perldoc Devel的修改示例:Refcount: use Devel::Peek;u
我正在阅读 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 referencen",Devel::Refcount::refcount($anon),Devel::Peek::SvREFCNT($anon);

my $otherref = $anon;

printf "Anon ARRAY $anon now has %d/%d referencesn",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=%dn",$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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读