There are a couple options. You need to know the
index, so foreach is out. You could do
something like this:
for(my $x = 0; $x <= $#array; $x++) {
next unless $array[$x];
# do stuff with $x and $array[$x]
}
But that is obviously inefficient, especially
if your list is VERY sparse. Like with elements
numbered 100, 435, 1040, etc.
Why not use a hash? You can convert a sparse
list to a hash like so:
my %hash =
map { $x => $y }
grep { my $y = $list[$x]; $y ne $undef; [$x, $y] }
for(my $x = 0; $x <= $#list; $x++);
And use it like this:
$list{100} = 'dog';
$list{435} = 'cat';
$list{1040} = 'tax form';
while(($index, $element) = each %list) {
# do stuff with $index and $element
}
Other alternatives include using a pseudohash,
or writing a tied array implementation
that acts like a list in your code but works like
a hash behind the scenes.
Good luck! |