Over the last few days I have twice seen answers to questions on this site advocating a foreach loop construct which has made me scratch my head somewhat. These answers have been in no way wrong, but, to my mind, promote code constructs which may lead to less maintainable code.

The foreach loop construct in question may be paraphrased thus:

foreach (1..5) { if ( $object->method( "arg$_" ) ) { # ... do stuff } }

The foreach loop iterates through a range of numbers, specified with either the range operator or a C-style for construct, using this loop index for construction of a parameter name or value through concatenation. That is, there is no use of the loop index as a storage index or reference, the loop using the index only for the creation of string values through concatenation.

This approach, to my mind, is very C-like and, in my humble opinion, could be better performed in the following manner:

foreach ( qw/ arg1 arg2 arg3 arg4 arg5 / ) { if ( $object->method( $_ ) ) { # ... do stuff } }

The difference between these foreach loop constructs is minor from a syntatical standpoint, but for foreach loop constructs where loop indices are being used only for the creation of string values through concatenation, this latter approach is advantageous primarily for reasons of on-going code maintenance.

That is, this latter approach:

It is for these first two reasons alone that I would advocate this latter approach to foreach loop constructs to improve the maintainability and usefulness of developed code.

I would welcome your comments and observations.

 

perl -e 'print+unpack("N",pack("B32","00000000000000000000000111001111")),"\n"'


In reply to On Foreach Loops and Maintainability by rob_au

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.