in reply to Re^4: The trouble with Perl Idiom
in thread The trouble with Perl Idiom

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.

Replies are listed 'Best First'.
Re^6: The trouble with Perl Idiom
by demerphq (Chancellor) on Aug 30, 2004 at 11:21 UTC

    Well I prefer the first two, although i would just use normal concatenation instead of the @{[]} (especially as its actually a char shorter :-), and i would put the for on the following line. The third example is interesting, I would probably go with your second implementation, but I can see the point you are making. Overall however I would say that the readability differences are so minimal that I would go for the more efficient of the statements. I know that folks get their knickers in a knot about premature optimisation, but I don't think is such a case.


    ---
    demerphq

      First they ignore you, then they laugh at you, then they fight you, then you win.
      -- Gandhi