[英]How do I store a 2d array in a hash in Perl?
我在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是一种非常有表现力的语言。 您可以使用以下语句完成所有操作。
$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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.