Search code examples
arraysperlfor-loopconditional-statementsdefined

In Perl, how can I find the last defined element in an array?


Using Perl, I wish to find the last element that is defined in an array.

So far I have the following:

#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;
    }
}

I'm not sure why this is not working. Any suggestions to improve, using Perl?


Solution

  • You need to start from 99 as 100 elements array has indexes: 0 .. 99. And break the loop as soon as you find the element:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    my @array = (1, 2, undef);
    
    my $lastdef;
    for (my $i = $#array; $i>=0; $i--) {
        if (defined($array[$i])){
            $lastdef=$i;
            last;
        }
    }
    
    print $lastdef;
    

    prints: 1