Interesting, I have no particular prejudice against such constructs, and find that I use them quite regularly. It all comes down to trying to write optimally-dense code, by which I mean the densest code that I [0] can easily grok at reading pace.

As such, it makes most sense when it reduces the loop action to a simple expression:

# build the dependency map for active children $child{$_} ||= $parent{$_} for grep $_->active, $self->children;
or:
warn "Deleting removed script '$_'\n" for map $_->name, @deleted;

It can also help by letting me put the important information into the name of the loop variable:

for my $hidden (grep !$_->visible, @objects) { ... }

In each of these cases, I think I can grasp the effect and intent of the code quicker than with an alternative that tries to avoid the construct:

# build the dependency map for active children $_->active and $child{$_} ||= $parent{$_} for $self->children; # (My brain doesn't grok 'condition and action' as fluently as # 'action if condition', but handles 'grep' fine.) warn "Deleting removed script '@{[ $_->name ]}'\n" for @deleted; # hmm, a minor difference, but @{[ ...]} is just too much punctuatio +n for my $object (@objects) { next if $object->visible; # below here '$object' is less informative ... } for my $hidden (@objects) { # '$hidden' is a lie here next if $hidden->visible; ... }

(Examples all taken from my work application, with minor edits.)

Hugo

[0] That is, myself or any suitable qualified other programmer who might look at my code in the future. My work code is not intended to be maintained by someone that doesn't know perl, and so isn't aimed to be readable for such a person.


In reply to Re^5: The trouble with Perl Idiom by hv
in thread The trouble with Perl Idiom by demerphq

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.