Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Re: "for" surprise

by Brutha (Friar)
on Nov 24, 2003 at 11:02 UTC ( [id://309490]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://309490]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2024-04-20 00:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found