Pregunta

Estoy luchando contra los objetos en Perl, y estoy tratando de crear una matriz 2D y almacenarla en un campo hash de mi objeto. Entiendo que para crear una matriz 2d necesito una matriz de referencias a las matrices, pero cuando intento hacerlo obtengo este error: El tipo de arg 1 que se debe empujar debe ser una matriz (no un elemento hash) El constructor funciona bien y set_seqs funciona bien, pero mi sub create_matrix está arrojando estos errores.

Esto es lo que estoy haciendo:

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

¿Alguna idea de lo que estoy haciendo mal?

¿Fue útil?

Solución

Te estás perdiendo un conjunto adicional de llaves cuando desreferencia $ self. Pruebe push @ {$ self- > {matrix}}, [] .

Cuando tenga dudas (si no está seguro de estar refiriéndose al valor correcto en una estructura de datos complicada), agregue más llaves. :) Consulte perldoc perlreftut .

Otros consejos

Perl es un muy expresivo, lenguaje. Puedes hacerlo todo con la siguiente declaración.

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

¿Es este golf? Tal vez, pero también evita mucking con el meticuloso prototipo push . Exploto la siguiente declaración:

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

Tengo una subrutina estándar para hacer tablas:

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

Y aquí hay una función de matriz de matrices más 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 bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top