我有一个Perl脚本生成一个对象的弱引用数组.一旦其中一个对象超出范围,数组中对它的引用将变为未定义.
ex(伪代码):
# Imagine an array of weak references to objects my @array = ( $obj1_ref,$obj2_ref,$obj3_ref ); # Some other code here causes the last strong reference # of $obj2_ref to go out of scope. # We now have the following array @array = ( $obj1_ref,undef,$obj3_ref )
是否有一种方法可以使未定义的引用在数组未定义时自动从数组中删除?
我想要@array =($obj1_red,$obj3_ref).
编辑:
我尝试了这个解决方案但它不起作用:
#!/usr/bin/perl use strict; use warnings; { package Object; sub new { my $class = shift; bless({ @_ },$class) } } { use Scalar::Util qw(weaken); use Data::Dumper; my $object = Object->new(); my $array; $array = sub { \@_ }->( grep defined,@$array ); { my $object = Object->new(); @$array = ('test1',$object,'test3'); weaken($array->[1]); print Dumper($array); } print Dumper($array);
输出:
$VAR1 = [ 'test1',bless( {},'Object' ),'test3' ]; $VAR1 = [ 'test1','test3' ];
我错过了什么吗?
编辑2:
I also tried removing undefined values from the array in the DESTROY method of the object,but that doesn’t appear to work either. It appears that since the object is still technically not “destroyed” yet,the weak references are still defined until the DESTROY method is completed…
解决方法
不,没有,没有使用魔法(例如绑定)阵列.
如果您对数组而不是数组有引用,则可以使用以下命令有效地过滤掉未定义的元素,而不“强化”任何引用.
$array = sub { \@_ }->( grep defined,@$array );
事实上,这根本不会复制值.只有“C指针”被复制.