如何在 Perl 中将二维数组存储在哈希中?
我正在 perl 中努力处理对象,并尝试创建一个二维数组并将其存储在对象的哈希字段中。我知道要创建一个二维数组,我需要一个对数组的引用的数组,但是当我尝试这样做时,我收到此错误:要推送的 arg 1 的类型必须是数组(不是哈希元素)
构造函数工作正常,并且 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}, []);
}
}
知道我做错了什么吗?
I am struggling through objects in perl, and am trying to create a 2d array and store it in a hash field of my object. I understand that to create a 2d array I need an array of references to arrays, but when I try to do it I get this error: Type of arg 1 to push must be array (not hash element)
The constructor works fine, and set_seqs
works fine, but my create_matrix
sub is throwing these errors.
Here is what I am doing:
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}, []);
}
}
Any idea of what I am doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Perl 是一种非常富有表现力的语言。您可以通过下面的语句来做到这一点。
这是高尔夫吗?也许吧,但它也避免了对挑剔的
push
原型的破坏。我分解下面的语句:我有一个标准的子例程来制作表格:
这是一个更通用的数组数组函数:
Perl is a very expressive, language. You can do that all with the statement below.
Is this golf? Maybe, but it also avoids mucking with the finicky
push
prototype. I explode the statement below:I have a standard subroutine to make tables:
And here's a more generalized array-of-arrays function:
当您取消引用 $self 时,您缺少一组额外的大括号。尝试
push @{$self->{matrix}}, []
。如有疑问(如果您不确定所引用的复杂数据结构中的值是否正确),请添加更多大括号。 :) 请参阅 perldoc perlreftut。
You're missing an extra set of braces when you dereference $self. Try
push @{$self->{matrix}}, []
.When in doubt (if you're not sure if you're referring to the correct value in a complicated data structure), add more braces. :) See perldoc perlreftut.