Since other people seem to only be suggesting the 'slice' implementation, I will follow in the spirit of Perl, and suggest a persuasive alternative:

for (my $i = 2; $i < @array; $i++) { local *_ = \ $array[$i]; ... use $_ as you would normally use it in foreach() ... }

The "local *_ = \ $scalar" trick makes $_ become an alias to $scalar (really the value in $scalar). This is equivalent to the effect that foreach() has, with the exception that this method does not work for lexical variables. UPDATE: Further explanation: foreach() accepts a lexical iterator variable. local(*) can only be used on global variables.

When would you use this alternative over the slice alternative? I would suggest that the slice alternative be used for all relatively simple operations that involve few array elements (<1000), and that can be easily represented using '..' notation. The slice solution is certainly more common, and therefore, easy to maintain.

The most significant problem with the slice alternative is that array slices are actually a list of scalars specified using a simplified notation. You can easily specify @array[1 .. 1000000], but the result is a temporary list that has 1000000 scalars in it. Unless you have relatively unlimited RAM, the alternative presented above may be for you. (NOTE: I wouldn't consider 100 elements to be large enough to avoid using '..' and an array slice)

A major benefit for the alternative presented above, is that the algorithm used to move through the array can be arbitrarily complicated. Backwards, forwards, skip by 2, etc. .

Have fun... :-)


In reply to Re: Starting foreach at an arbitrary position by MarkM
in thread Starting foreach at an arbitrary position by Anonymous Monk

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.