Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

The fact that the code in the bodies of the loops are quite different means that "better" can't meaningfully be applied. There are situations where the C style loop is "better", but in the general case the Perl style for loop is "better".

The C style for loop for (initialisation; condition; expression) {...} is equivalent to:

initialisation; while (condition) { ... } continue { expression }

where the three parts (initialisation, condition and expression) need not be related to each other in any way except they are all part of the same for loop header. That allows the C for loop to be abused in many ways. The clutter in the loop header often makes it difficult to see the various parts and the nature of the condition means that C style for loops are very prone to off by one errors.

The Perl for loop on the other hand is simple. All it does is iterate over a list of elements. The list may be the contents of an array, or the members of a list generated using the range operator or something tricky using map, grep or whatever, but always the Perl for loop simply iterates over a list. (Internally the for loop code may employ various tricks to improve memory usage or speed, but those are unimportant to our current discussion.)

It is worth remembering that the Perl for loop can be used as a statement modifier so your loop could be:

push @cleaned_values, _clean_cgi_param ($_) for @values;

Perl reduces RSI - it saves typing

In reply to Re: C-style for loop by GrandFather
in thread C-style for loop by mandog

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2024-04-20 01:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found