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. |