在Perl中,如何在数组中找到最后定义的元素?

use*_*165 2 arrays perl for-loop defined conditional-statements

使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我不确定为什么这不起作用.有什么建议要改进,使用Perl?

TLP*_*TLP 10

我不确定为什么这不起作用.有什么建议要改进,使用Perl?

你不知道它为什么不起作用的原因是因为你没有使用

use warnings;
Run Code Online (Sandbox Code Playgroud)

如果你有,你会被告知:

Use of uninitialized value in numeric ne (!=) at ...
Run Code Online (Sandbox Code Playgroud)

因为!=数字不等式运算符,它会将其参数转换为数字.如果您没有warnings打开,则会以静默方式转换undef0.毋庸置疑,warnings开启是一件非常好的事情,所以你不要犯这样的错误.

就是这条线:

if (($array[$i] != undef) ...
Run Code Online (Sandbox Code Playgroud)

那应该是

if ((defined($array[$i]) ...
Run Code Online (Sandbox Code Playgroud)

因为它是defined检查定义值的函数.这是一个奇怪的错误,因为你甚至在同一行上使用相同的功能.

此外,您可以通过这样做更简单

if (defined($array[$i])) {
     $lastdef = $i;
     last;
}
Run Code Online (Sandbox Code Playgroud)

last 这将在找到第一个未定义值时结束循环.

您还应该知道在循环条件下可以使用非硬编码的最大值:

for (my $i = $#array; $i >= 0; $i--) {
Run Code Online (Sandbox Code Playgroud)

$#array 包含数组中现有最高索引的编号.