On Wed, 6 Feb 2002, Carl Rogers wrote:

> Good day;
>
> I'm using foreach to do something to an array. is there a way I can
> reference a previously 'seen' element without having to traverse the array
> with a for(;;) statement?
>
> ie. I'd like this to work:
>
> foreach(@array) {
>
>       if ($_ =~/somecondition/) {
>       # I want to do something to the element prior to $_ ($_ - 1)
>       }
> }

The problem here is that $_ is a *copy* of the element in the array --
modifying it does not modify the array (I think in earlier versions it was
actually an alias, which, I have read, led to all sorts of abuse), so
without some kind of a counter, you will not have any knowledge of the
previous value.

You can avoid using the C-ish for loop and use a Perlish one (for is an
alias for foreach... or is it the other way around?), if you want to
actually modify something in the array:

foreach(0..$#array) {
  if ($array[$_] =~ /something/) {
        $array[$_ - 1] = 'something';
}

-- Brett
                                          http://www.chapelperilous.net/
------------------------------------------------------------------------
If God had intended Man to Watch TV, He would have given him Rabbit Ears.


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to