2011-03-31 67 views
1

我有一个将数组存储为实例变量的对象。由于Perl似乎不支持这一点,我必须将引用存储到数组中。但是,我无法弄清楚如何在创建这些数组后再进行变异。这些方法似乎只会改变本地副本。 (目前,在addOwnedFile()的末尾,对象数据保持不变)。Perl中的数组访问器方法

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; 
} 
+1

阅读[perldoc perlref](http://perldoc.perl.org/perlref.html)和[perldoc perlreftut](http://perldoc.perl.org/perlreftut.html) – 2011-03-31 02:15:25

回答

8

您发布的代码触发运行“不是一个数组引用...”错误。原因是设置_owned_files\[]这不是数组引用,而是对数组引用的引用。从两个数组属性中删除\

因为这样,我们可以解决下一个问题。 @array是由对象持有的匿名数组的副本。你的前两个push es是复制,最后一个是保存的数组。然后,通过将其替换为对副本的引用来重新触发所保存的数组。最好只通过参考与原始数组一起工作。下面的任一会的工作:

push @$ref, 'something'; 
push @{$self->{_owned_files}}, 'something'; 

,并在年底下降了

$self->{_owned_files} = \@array; 

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; 
} 
0

我相当肯定你在

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

部分的问题。 _owned_file=> \[]不会创建和数组引用,而是对数组引用的引用。而你想要的是_owned_files => []。共享文件相同。

+0

嗯,它不似乎工作,与[],\()或\ @ owned_arrays。我也尝试过@ @ ref“something”。 – chimeracoder 2011-03-31 01:26:13