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

数组 – 自删除数组元素(一旦它们变为未定义)

发布时间:2020-12-16 06:13:47 所属栏目:大数据 来源:网络整理
导读:我有一个Perl脚本生成一个对象的弱引用数组.一旦其中一个对象超出范围,数组中对它的引用将变为未定义. ex(伪代码): # Imagine an array of weak references to objectsmy @array = ( $obj1_ref,$obj2_ref,$obj3_ref );# Some other code here causes the la
我有一个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'
        ];

undef不会自动从阵列中删除.

我错过了什么吗?

编辑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指针”被复制.

(编辑:李大同)

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

    推荐文章
      热点阅读