Perl中数组的访问器方法

chi*_*der 1 oop perl

我有一个对象将数组存储为实例变量.由于Perl似乎不支持这一点,我必须存储对数组的引用.但是,我无法弄清楚如何在创建这些数组后改变这些数组; 这些方法似乎只改变了本地副本.(目前,在addOwnedFile()结束时,对象数据不变).

sub new {
    my ($class) = @_;
    my @owned_files = ();
    my @shared_files = ();

    my $self = {

        #$[0] is the class
        _name => $_[1],
        _owned_files => \[],
        _shared_files => \[],        
    };
    bless $self, $class;

    return $self;
    }




#Add a file to the list of files that a user owns
sub addOwnedFile {
    my ($self, $file) = @_;
        my $ref = $self -> {_owned_files};
        my @array = @$ref;

        push(@array, $file);

        push(@array, "something");

        push(@{$self->{_owned_files}}, "something else");

        $self->{_owned_files} = \@array;
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*man 8

您发布的代码触发运行时"Not a ARRAY reference ..."错误.其原因是,设置_owned_files\[]这不是一个数组引用而是数组引用的引用.删除\两个数组属性.

有了这个,我们可以解决下一个问题.@array是对象持有的匿名数组的副本.您的前两个push是复制,最后一个是保持的数组.然后,通过将其替换为对副本的引用来破坏保留的数组.最好通过引用处理原始数组.以下任何一种都可以工作:

push @$ref, 'something';
push @{$self->{_owned_files}}, 'something';
Run Code Online (Sandbox Code Playgroud)

然后放弃

$self->{_owned_files} = \@array;
Run Code Online (Sandbox Code Playgroud)

在末尾.

sub new {
    my $class = shift;
    my $name  = shift;
    my $self  = {
        _name         => $name,
        _owned_files  => [],
        _shared_files => [],
    };
    return bless $self, $class;
}

sub addOwnedFile {
    my ($self, $file) = @_;
    push @{$self->{_shared_files}}, $file;
}
Run Code Online (Sandbox Code Playgroud)