使用 Perl,我希望找到数组中定义的最后一个元素。
到目前为止,我有以下内容:
#generating array
$array[100] = (undef);
$array[$columns[1]-1] = $columns [2];
#finding the last element that is defined
for ($i=100; $i>=0; $i--) {
if (($array[$i] != undef) && (!defined($lastdef)) ){
$lastdef=$i;
}
}
我不知道为什么这不起作用。使用 Perl 有任何改进建议吗?
最佳答案
I'm not sure why this is not working. Any suggestions to improve, using Perl?
你不知道它为什么不起作用的原因是你没有使用
use warnings;
如果你这样做了,你会被告知:
Use of uninitialized value in numeric ne (!=) at ...
因为!=
是numeric inequality operator ,它会将其参数转换为数字。如果您没有打开警告
,这会默默地将undef
转换为0
。不用说,打开警告
是一件非常好的事情,这样你就不会犯这样的错误。
就是这一行:
if (($array[$i] != undef) ...
应该是这样
if ((defined($array[$i]) ...
因为它是define
函数来检查值的定义性。这是一个奇怪的错误,因为您甚至在同一行上使用相同的函数。
此外,您可以通过执行以下操作来简化此操作
if (defined($array[$i])) {
$lastdef = $i;
last;
}
last
将在找到第一个未定义值时结束循环。
您还应该知道,您可以在循环条件上使用非硬编码的最大值:
for (my $i = $#array; $i >= 0; $i--) {
$#array
包含数组中现有的最高索引的编号。
关于arrays - 在 Perl 中,如何找到数组中最后定义的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17899687/