- 当
@a被回收时,values的refcount都会减1。
- 当匿名数组/哈希的
refcount为0时,将被回收,同时递归进行步骤1
所以:
@a = ({1,2,3}, [1,2,3]);
当@a被回收时,{1,2,3}和[1,2,3]的refcount都将变为0,从而将被回收。
可以通过对象的destructor来验证这一点:
perl -e'
{
package X ;
sub new { my ($c,$n) = @_; bless(\$n, $c) }
DESTROY { print ${$_[0]},"\n"; }
{
my @a = (
{ a => X->new(1), b => X->new(2) },
[ X->new(3), X->new(4) ],
);
print "Before end of scope\n";
}
print "After end of scope\n";
}
'
输出是:
Before end of scope
4
3
2
1
After end of scope
要特别注意的是对于%hash只会对其values进行refcount减1(当把引用用作key时,会被转为字符串,同时立马refcount减1):
perl -e'
{
package X ;
sub new { my ($c,$n) = @_; bless(\$n, $c) }
DESTROY { print ${$_[0]},"\n"; }
{
my @a = (
{ X->new(1), X->new(2) },
[ X->new(3), X->new(4) ],
);
print "Before end of scope\n";
}
print "After end of scope\n";
}
'
输出:
1
Before end of scope
4
3
2
After end of scope