I'm not sure why this is not working. Any suggestions to improve, using Perl?
The reason you don't know why it is not working is because you are not using
use warnings;
If you had, you would have been told:
Use of uninitialized value in numeric ne (!=) at ...
Because !=
is the numeric inequality operator, and it will convert its parameters to numbers. If you do not have warnings
turned on, this will silently convert undef
to 0
. Needless to say, having warnings
turned on is a very good thing, so that you do not make mistakes like this.
It is this line:
if (($array[$i] != undef) ...
That should be
if ((defined($array[$i]) ...
Because it is the defined
function that checks a value for definedness. It is an odd mistake to make, since you even use that same function on the same line.
Also, you can make this simpler by doing
if (defined($array[$i])) {
$lastdef = $i;
last;
}
last
will here end the loop when the first undefined value is found.
You should also know that you can use a non-hardcoded max value on your loop condition:
for (my $i = $#array; $i >= 0; $i--) {
$#array
contains the number of the highest existing index in your array.