Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An elegant way of returning the index of the last non-zero element in Perl?

Tags:

arrays

perl

I find myself wanting to find the index of the last non-zero element in an array. So, given:

my @array = (0,0,5,9,0,0,0,7,0,3,0,0);
my $indexLastNonZero = insertElegantMethodHere(@array);
# expect $indexLastNonZero to be equal to 9;

I've done this:

for my $i (0 .. $#array) {
    $indexLastNonZero = $i if $array[$i] != 0;
};

I works but somehow I can't help feel there must be a super elegant (smarter? nice? more efficient?) way of doing this in perl. I've looked into List::Utils but not found a nice way there and would like a non-core-module independent method.

Any thoughts?

Cheers

like image 256
moigescr Avatar asked Nov 29 '22 07:11

moigescr


1 Answers

Use List::MoreUtils for such tasks:

use warnings;
use strict;

use List::MoreUtils;

my @array = (0,0,5,9,0,0,0,7,0,3,0,0);

print List::MoreUtils::lastidx { $_ } @array
like image 60
René Nyffenegger Avatar answered Dec 16 '22 08:12

René Nyffenegger