http://qs321.pair.com?node_id=723845


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