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!

In reply to Re: Efficient access to sparse lists? by mwp
in thread Efficient access to sparse lists? by Improv

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.