Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am using a "foreach" to loop over every element, and call last as soon as I find a match. This is stored in a variable and I would like to store the preceeding list element in a seperate variable. Any tips?

Originally posted as a Categorized Question.

  • Comment on How do I find the array element directly preceeding a 'match'?

Replies are listed 'Best First'.
Re: How do I find the array element directly preceeding a 'match'?
by amelinda (Friar) on Oct 13, 2000 at 03:30 UTC
    Try this:
    foreach $item (@array) { if (matches($item)) { $found = $last; last; } $last = $item; }
    where $last holds the "preceeding list element" of the current item and $found holds the "preceeding list element" of the item that matches.

Re: How do I find the array element directly preceeding a 'match'?
by ton (Friar) on Apr 05, 2001 at 03:39 UTC
    Or you could just use a for loop, and eliminate the need for multiple assignments:
    for ($i=0; $i<scalar(@array); ++$i) { last if (matches($array[$i])); } $found = $array[$i-1] if ($i);
Re: How do I find the array element directly preceeding a
by Fastolfe (Vicar) on Oct 13, 2000 at 00:49 UTC
    The "correct" solution is to iterate through the indexes, not the elements themselves:
    for ($i = 0; $i < @array; $i++) { if (matches($array[$i])) { $found = $array[$i-1]; } }
    If you want to insist doing it in foreach style:
    foreach $item (@array) { if (matches($item)) { $found = $last; } $last = $item; }

    Originally posted as a Categorized Answer.

Re: How do I find the array element directly preceeding a
by merlyn (Sage) on Oct 13, 2000 at 10:46 UTC
    for ($i = 0; $i < @array; $i++) { if (matches($array[$i])) { $found = $array[$i-1]; } }
    Ugh. What if $i = 0 at the match? You've just indexed into the end of the array? Either start at 1, or redefine your problem for the unusual case.

    Originally posted as a Categorized Answer.