in reply to "for" surprise

Can you let us know what it was you were trying to do with this code or similar?

I get the impression there's something else going on, because as presented here, the code is pretty illogical. Why make $i 45, then make it 0 two lines later?



($_='kkvvttuubbooppuuiiffssqqffssmmiibbddllffss') =~y~b-v~a-z~s; print

Replies are listed 'Best First'.
Re: Re: "for" surprise
by Brutha (Friar) on Nov 24, 2003 at 11:02 UTC
    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)

      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.