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

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

Thread Previous | Thread Next
Brett W. McCoy
February 6, 2002 13:55
Re: Accessing previous element of an array in a 'foreach' loop
Message ID:
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
If God had intended Man to Watch TV, He would have given him Rabbit Ears.

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About