Pergunta

Eu estou lutando através de objetos em Perl, e estou tentando criar uma matriz 2D e armazená-lo em um campo de hash do meu objeto. Eu entendo que para criar uma matriz 2d eu preciso uma série de referências a matrizes, mas quando eu tento fazê-lo eu recebo este erro: Type of arg 1 to push must be array (not hash element) O construtor funciona bem, e set_seqs funciona bem, mas o meu create_matrix sub está jogando esses erros <. / p>

Aqui está o que eu estou fazendo:

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}, []);
    }
}

Qualquer idéia do que estou fazendo de errado?

Foi útil?

Solução

Você está perdendo um jogo extra de chaves quando você desreferenciava $ self. Tente push @{$self->{matrix}}, [].

Em caso de dúvida (se você não tem certeza se você está se referindo ao valor correto em uma estrutura de dados complicado), adicionar mais chaves. :) Veja perldoc perlreftut .

Outras dicas

Perl é uma muito expressivo, língua. Você pode fazer isso tudo com a declaração abaixo.

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

É este o golf? Talvez, mas também evita sujar com o protótipo push exigente. I explodir a declaração abaixo:

$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.

Eu tenho uma sub-rotina padrão para fazer tabelas:

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

E aqui está uma função de matriz-de-matrizes mais generalizada:

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 ];
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top