【问题标题】:array deepcopy instead of reference in perl object数组 deepcopy 而不是 perl 对象中的引用
【发布时间】:2012-10-17 21:27:31
【问题描述】:

我尝试了几个小时将子数组存储到对象中但失败了。也许你们中的某个人可以向我展示如何使用 perl 存储深层副本。 对不起,我不知道这个问题是否清楚,但应该很容易解决......

这里是例子。

这里是对象类

package obj;

use strict;
use warnings;
require Exporter;
our @ISA = qw(Exporter);

sub new(\@){
    my $class=shift;
    my $this={};
    $this->{"array"}=shift;
    return bless($this,$class);
}

sub getArray(){
    my $this=shift;
    return $this->{"array"};
}

和测试类

use strict;
use warnings;
use obj;

my @a=(1,2);
push @a,3;
my $ob=obj->new(\@a);
@a=();
print @{$ob->getArray()};

这不返回任何内容 - 不移动取消引用数组?

那该怎么做呢?

谢谢

【问题讨论】:

    标签: perl object reference deep-copy


    【解决方案1】:

    尊重什么数组?移位中涉及的唯一数组是@_? $_[0] 是一个标量,而不是一个数组。

    使用以下方法完成(浅)数组复制:

    @dst = @src;
    

    你想要的

    @{ $this->{"array"} } = @{ shift };
    

    如果您真的想要一个深层副本(尽管在您的示例中不需要它),请使用

    use Storable qw( dclone );
    
    $this->{"array"} = dclone(shift);
    

    【讨论】:

    • 或通过以下方式进行浅拷贝:$this->{'array'} = [ @{ shift } ]
    • 如果我这样做,输出将变成一个标量,并且它只返回第一个数组元素 1。我认为深拷贝是必要的,因为我覆盖了 @a=()。所以引用的数组消失了。使用可存储的 qw(dclone);做我想做的。谢谢
    • @pyr0,我不知道你指的是我的代码还是ysth,但都没有复制数组的单个元素。
    猜你喜欢
    • 1970-01-01
    • 2022-01-17
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多