in reply to Re: "for" surprise
in thread "for" surprise

One of the cases, when I use similar constructs is a linear search on an array, you stop, when you found an entry. You scan the entries of an array one after the other, jump out of the loop, when you found something. After the loop, you examine the index. If it is lower than the endvalue of the loop, you found something at the index:

my $i; for ($i=0; $i<=$#list; $i++) { last if found_it( $list[$i] ); } print "Found at position $i\n" if ($i <= $#list);
(Of course, code is simplified and not tested)

And it came to pass that in time the Great God Om spake unto Brutha, the Chosen One: "Psst!"
(Terry Pratchett, Small Gods)

Replies are listed 'Best First'.
Re: Re: Re: "for" surprise
by podian (Scribe) on Nov 24, 2003 at 18:18 UTC
    why not move everything to a function and let the function return the index where the data is found?
    sub search{ my ($item,$end) = @_; my $i; my $found = 1; foreach $i (0..$end) { if (some condition on the list){ return ($found, $i); } } return (0,0); }

    since perl supports multiple return values, we could return $found as well if someone wants it.