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

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

Thread Previous
From:
Jeff 'japhy' Pinyan
Date:
February 6, 2002 13:55
Subject:
Re: Accessing previous element of an array in a 'foreach' loop
Message ID:
Pine.GSO.4.21.0202061653190.612-100000@crusoe.crusoe.net
On Feb 6, Carl Rogers said:

>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)
>	}
>}

Just keep track of the previous element.

  my $is_first_iter = 1;
  my $prev_ele;

  for (@array) {
    if ($is_first_iter) {
      $prev_ele = $_;
      $is_first_iter = 0;
      next;
    }

    if (/condition/) {
      # fiddle with $prev_ele
    }

    $prev_ele = $_;
  }

-- 
Jeff "japhy" Pinyan      japhy@pobox.com      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
** Look for "Regular Expressions in Perl" published by Manning, in 2002 **
<stu> what does y/// stand for?  <tenderpuss> why, yansliterate of course.


Thread Previous


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