gpt4 book ai didi

perl:为什么 Devel::Refcount::refcount 和 Devel::Peek::SvREFCNT 不一致?

转载 作者:行者123 更新时间:2023-12-03 20:46:06 26 4
gpt4 key购买 nike

我在看 How can I access the ref count of a Perl hash? , 并且都有 Devel::Refcount::refcountDevel::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::Refcount::refcount($anon),
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', $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 不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11344518/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com