我正在穿越perl中的对象,我正在尝试创建一个二维数组并将其存储在我的对象的哈希字段中。我知道要创建一个二维数组我需要一个对数组的引用数组,但是当我尝试这样做时我得到了这个错误:Type of arg 1 to push must be array (not hash element)
构造函数工作正常,set_seqs
工作正常,但我的create_matrix
sub正在抛出这些错误。
这是我正在做的事情:
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}, []);
}
}
知道我做错了什么?
答案 0 :(得分:4)
当你取消引用$ self时,你错过了额外的一组括号。试试push @{$self->{matrix}}, []
。
如果有疑问(如果您不确定是否在复杂的数据结构中引用了正确的值),请添加更多大括号。 :)见perldoc perlreftut。
答案 1 :(得分:3)
Perl是一种非常富有表现力的语言。您可以使用下面的语句完成所有操作。
$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;
}
答案 2 :(得分:2)
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 ];
}
}