in reply to Starting foreach at an arbitrary position
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... :-)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Starting foreach at an arbitrary position
by Aristotle (Chancellor) on Jan 18, 2003 at 17:33 UTC | |
|
Re: Re: Starting foreach at an arbitrary position
by sauoq (Abbot) on Jan 19, 2003 at 04:07 UTC | |
by theorbtwo (Prior) on Jan 19, 2003 at 04:12 UTC | |
by sauoq (Abbot) on Jan 19, 2003 at 04:24 UTC |