Here's the bare logic of a stripped-down solution modelled after your approach (let's make it self-contained for testing purposes):
But we're continuing to loop even after we find the correct element. Wasted work. So we need to track things a little more carefully. Perhaps something like this (leaving out the loop variable just for fun):my $goal = 'over'; my @array = qw(the quick fox jumped over the lazy dog); foreach my $item (@array) { next unless $item =~ /$goal/; print $item; }
But what if you still want to know after the loop if the search succeeded and use that value...my $goal = 'over'; my @array = qw(the quick fox jumped over the lazy dog); for (@array) { next unless /$goal/; print $_; last }
Or you could wrap the if block inside the loop like this:my $goal = 'over'; my @array = qw(the quick fox jumped over the lazy dog); my $found_item; foreach my $item (@array) { next unless $item =~ /$goal/; $found_item = $item; last; } if ($found_item) { print $found_item; # do other stuff }
In this case $item goes out of scope at the end of the loop and is irretrevable for use after that. Which is tidy if you don't need it later or annoying if you do.my $goal = 'over'; my @array = qw(the quick fox jumped over the lazy dog); my $found; foreach my $item (@array) { if ($item =~ /$goal/) { $found = 1; # in case we need it later print $item; # do other stuff last; } }
Somewhere among those Ways To Do It you should find something that matches your need. HTH ...David
In reply to Re: skipping until an alement is matched
by dvergin
in thread skipping until an alement is matched
by Amoe
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |