Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: C-style for loop

by GrandFather (Saint)
on Nov 15, 2008 at 20:21 UTC ( #723845=note: print w/replies, xml ) Need Help??


in reply to C-style for loop

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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2021-02-27 02:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?