2011-03-31 2 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)을 읽으십시오. –

답변

8

당신이 게시 코드는 런타임 "뿐만 배열 참조 ..." 오류를 트리거합니다. 이유는 배열 참조가 아니라 배열 참조에 대한 참조 인 _owned_files ~ \[] 집합입니다. 두 배열 속성에서 \을 삭제하십시오.

그걸로 우리는 다음 문제에 도달 할 수 있습니다. @array은 개체가 보유하는 익명 배열의 복사본입니다. 첫 번째 두 개의 push이 복사 대상 배열의 마지막 배열입니다. 보류 된 배열을 복사본에 대한 참조로 바꾸어 보관합니다. 참조를 통해 원래 배열로 작업하는 것이 가장 좋습니다. 다음 중 하나가 작동합니다 :

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로 작동하는 것 같습니다. 또한 push @ $ ref "something"을 시도했습니다. – chimeracoder

관련 문제