Come posso archiviare un array 2d in un hash in Perl?
-
05-07-2019 - |
Domanda
Sto lottando tra gli oggetti in perl e sto cercando di creare un array 2d e memorizzarlo in un campo hash del mio oggetto. Capisco che per creare un array 2d ho bisogno di un array di riferimenti ad array, ma quando provo a farlo ottengo questo errore: Il tipo di arg 1 da inviare deve essere array (non elemento hash)
Il costruttore funziona bene e set_seqs
funziona bene, ma il mio sub create_matrix
sta lanciando questi errori.
Ecco cosa sto facendo:
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}, []);
}
}
Qualche idea di cosa sto facendo di sbagliato?
Soluzione
Ti manca un set extra di parentesi graffe quando fai la dereference $ self. Prova push @ {$ self- > {matrix}}, []
.
In caso di dubbio (se non si è sicuri di riferirsi al valore corretto in una struttura di dati complicata), aggiungere più parentesi graffe. :) Vedi perldoc perlreftut .
Altri suggerimenti
Perl è un molto linguaggio espressivo. Puoi farlo tutto con la seguente dichiarazione.
$self->{matrix} = [ map { [ (0) x $seq2 ] } 1..$seq1 ];
Questo golf è? Forse, ma anche evita di perdere tempo con il prototipo push
. Esplodo la seguente dichiarazione:
$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.
Ho una subroutine standard per creare tabelle:
sub make_matrix {
my ( $dim1, $dim2 ) = @_;
my @table = map { [ ( 0 ) x $dim2 ] } 1..$dim1;
return wantarray? @table : \@table;
}
Ed ecco una funzione array-of-array più generalizzata:
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 ];
}
}