문제

나는 Perl의 물체를 통해 고군분투하고 있으며 2D 배열을 만들어 내 객체의 해시 필드에 저장하려고합니다. 2D 배열을 만들려면 배열에 대한 참조 배열이 필요하다는 것을 이해하지만, 그렇게하려고 할 때이 오류가 발생합니다. Type of arg 1 to push must be array (not hash element) 생성자는 잘 작동합니다 set_seqs 잘 작동하지만 내 create_matrix 서브는 이러한 오류를 던지고 있습니다.

여기에 내가하는 일이 있습니다.

sub new {
    my ($class) = @_;
    my $self = {};
    $self->{seq1} = undef;
    $self->{seq2} = undef;
    $self->{matrix} = ();
    bless($self, $class);
    return $self;
}
sub set_seqs {
    my $self = shift;
    $self->{seq1} = shift;
    $self->{seq2} = shift;
    print $self->{seq1};
}

sub create_matrix {
    my $self = shift;
    $self->set_seqs(shift, shift);
    #create the 2d array of scores
    #to create a matrix:
    #create a 2d array of length [lengthofseq1][lengthofseq2]
    for (my $i = 0; $i < length($self->{seq1}) - 1; $i++) {
        #push a new array reference onto the matrix
        #this line generates the error
        push(@$self->{matrix}, []);
    }
}

내가 무엇을 잘못하고 있는지에 대한 아이디어가 있습니까?

도움이 되었습니까?

해결책

당신은 당신이 $ self를 불러 일으킬 때 여분의 교정기 세트를 놓치고 있습니다. 노력하다 push @{$self->{matrix}}, [].

의심스러운 경우 (복잡한 데이터 구조에서 올바른 값을 언급하는지 확실하지 않은 경우) 더 많은 브레이스를 추가하십시오. :) 보다 Perldoc Perlreftut.

다른 팁

Perl은 a입니다 매우 표현력, 언어. 아래의 진술과 함께 모든 것을 할 수 있습니다.

$self->{matrix} = [ map { [ (0) x $seq2 ] } 1..$seq1 ];

이 골프입니까? 어쩌면 또한 까다로운 소리를 피하십시오 push 원기. 아래의 진술을 폭발시킵니다.

$self->{matrix} = [     # we want an array reference
    map {               # create a derivative list from the list you will pass it
        [ (0) x $seq2 ] # another array reference, using the *repeat* operator 
                        # in it's list form, thus creating a list of 0's as 
                        # long as the value given by $seq2, to fill out the  
                        # reference's values.
   } 
   1..$seq1             # we're not using the indexes as anything more than  
                        # control, so, use them base-1.
];                       # a completed array of arrays.

테이블을 만들기위한 표준 서브 루틴이 있습니다.

sub make_matrix { 
    my ( $dim1, $dim2 ) = @_;
    my @table = map { [ ( 0 ) x $dim2 ] } 1..$dim1;
    return wantarray? @table : \@table;
}

그리고 다음은보다 일반화 된 배열 기능이 있습니다.

sub multidimensional_array { 
    my $dim = shift;
    return [ ( 0 ) x $dim ] unless @_; # edge case

    my @table = map { scalar multidimensional_array( @_ ) } 1..$dim;
    return wantarray ? @table : \@table;
}
sub create_matrix {
    my($self,$seq1,$seq2) = @_;
    $self->set_seqs($seq2, $seq2);

    #create the 2d array of scores
    #to create a matrix:
    #create a 2d array of length [$seq1][$seq2]
    for( 1..$seq1 ){
        push @{$self->{matrix}}, [ (undef) x $seq2 ];
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top