这个 Perl 子程序有什么问题? [英] What is wrong with this Perl subroutine?
问题描述
我正在尝试实现一个计算输入字符串的 d-neighbors 的子程序.这是种植主题搜索的一部分,但我的问题更笼统.代码如下:
I'm trying to implement a subroutine that calculates the d-neighbors of an input string. This is apart of an implementation of planted motif search, but my question is much more general. Here is the code:
#subroutine for generating d-neighbors
sub generate_d_neighbors{
# $sequence is the sequence to generate d-neighbors from
# $HD is the Hamming Distance
my ($sequence, $HD) = @_;
for(my $i = 0; $i=$HD; $i++){
my @l = ['A', 'C', 'T', 'G'];
my @t = splice(@l,$sequence[$i]);
#TODO
}
}
错误发生在最后一行,说明:
The error is occurring at the last line, saying that:
全局符号@sequence"需要明确的包名(你忘记声明我的@sequence"了吗?
据我所知,Perl 不像在 Java 中那样采用 subroutine(param1, param2)
形式的参数,但是为什么 $sequence
不被识别是否已经初始化?
It was my understanding that Perl does not take parameters in the form subroutine(param1, param2)
like in Java for example, but why is $sequence
not being recognized as already having been initialized?
推荐答案
您的代码存在一些问题:
There are some problems with your code:
sub generate_d_neighbors{
my ($sequence, $HD) = @_;
for(my $i = 0; $i=$HD; $i++){
my @l = ['A', 'C', 'T', 'G'];
my @t = splice(@l,$sequence[$i]);
}
}
首先,我们来看看
for(my $i = 0; $i=$HD; $i++){
假设 $HD
非零,这个循环永远不会终止,因为条件永远不会为假.如果您希望 $i
的范围从 0
到 $HD
,请将语句写为 for my $i (0 .. $HD)
会更好.
Assuming $HD
is nonzero, this loop will never terminate because the condition will never be false. If you wanted $i
to range from 0
to $HD
, writing the statement as for my $i (0 .. $HD)
would have been better.
第二,你有</p>
Second, you have
my @t = splice(@l,$sequence[$i]);
您似乎假设有一个数组 @sequence
并且您正试图访问它的第一个元素.但是,$sequence
是对数组的引用.因此,您应该使用
where you seem to assume there is an array @sequence
and you are trying to access its first element. However, $sequence
is a reference to an array. Therefore, you should use
$sequence->[$i]
第三(感谢@Ikegami),你有
Third (thanks @Ikegami), you have
my @l = ['A', 'C', 'T', 'G'];
在 for
循环的主体中.然后 @l
将包含单个元素,对包含元素 'A'
, 'C'
, 的匿名数组的引用'T'
和 'G'
.相反,请使用:
in the body of the for
-loop. Then @l
will contain a single element, a reference to an anonymous array containing the elements 'A'
, 'C'
, 'T'
, and 'G'
. Instead, use:
my @l = qw(A C T G);
我不确定你想用 splice(@l, $sequence->[$i])
实现什么,但可以更好地写成:
I am not sure exactly what you want to achieve with splice(@l, $sequence->[$i])
, but that can be better written as:
my @t = @l[0 .. ($sequence->[$i] - 1)];
实际上,您可以将两个分配减少为:
In fact, you could reduce the two assignments to:
my @t = qw(A C T G)[0 .. ($sequence->[$i] - 1)];
这篇关于这个 Perl 子程序有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!