develooper Front page | perl.beginners | Postings from February 2002

Re: Accessing previous element of an array in a 'foreach' loop

Thread Previous | Thread Next
From:
Brett W. McCoy
Date:
February 6, 2002 13:55
Subject:
Re: Accessing previous element of an array in a 'foreach' loop
Message ID:
Pine.LNX.4.43.0202061658200.17062-100000@chapelperilous.net
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.


Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About