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

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

Thread Next
From:
Carl Rogers
Date:
February 6, 2002 13:43
Subject:
Accessing previous element of an array in a 'foreach' loop
Message ID:
5.0.2.1.0.20020206162309.00a13020@pop3.norton.antivirus
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)
	}
}

However, I know I can use

for($x=0, $x<$#array; $x++){
  	if($array[$x] =~ /somecondition/){
	# do something to $array[$x-1]
	}

}

but I'm curious if there is a way to do the same in the foreach loop.

Thank you very much for your time.
Carl


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