Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re^7: loop surprise

by Skeeve (Parson)
on Apr 04, 2018 at 10:02 UTC ( [id://1212309]=note: print w/replies, xml ) Need Help??


in reply to Re^6: loop surprise
in thread loop surprise

I can remember that long time (say: 30 or more years) ago, I also wrote loops like that.

But now that you mention it, and thinking about it, I notice always write those kind of loops like:

my $interesting_index= 'not existing'; for ($i=1; $i<=10; ++$i) { next unless &condition($i); $interesting_index= $i; last; } # spit an error if $interesting_index is still 'not existing'

The reason behind this is simply that your loop might not have found a valid value.


s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
+.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e

Replies are listed 'Best First'.
Re^8: loop surprise
by Marshall (Canon) on Apr 04, 2018 at 17:59 UTC
    There are many variants of how to do this. My inclination might be:
    my $interesting_index; my $i = 0; while (!defined($interesting_index) and $i++ <= 10) { $interesting_index = $i if condition($i); } # spit an error if $interesting_index is still 'not defined'
    If the purpose of the loop is to find an index, then I would try to make that fact prominent at the start of the loop. That way you don't have to read the body of the code to figure out the purpose/intent.

    In Perl often there are other ways to do something similar to this functionality with the various List::utils. My Perl code rarely uses any $i subscripts.

    update: maybe I have an "off by one" error in original post. I think it is also possible to use the C style loop:

    for (my $i=1; !defined($interesting_index) and $i<=10; $i++){}

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (3)
As of 2024-04-18 19:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found