loop

inkdroid on 2002-11-06T20:56:26

Peeking over petdance's shoulder I spied this gem:

s/a/z/g for @array;

I guess this sort of loop might be old hat, but I'd never seen it before.

Ahhh, Perl5....


That looks like transliteration.

brian_d_foy on 2002-11-06T21:29:11

# TIMTOWTDI :)
tr/a/z/ for @array;

Those sorts of loops always seem to mess with my mind though, and eventually I want to add another statement, so I always end up using the more common block form.

foreach ( @array )
        {
        warn "Working on [$_]\n" if $Debug;
        tr/a/z/;
        warn "\tnow it is [$_]\n";
        }

print() is the best debugger ever invented. :)

Various people have tried to convince me that I should optimize my keystrokes, but when I look at the parts of the coding process that I spend the most time in (maintenance), I realize that those little savings cost more time later, at least for me. I have used those statement modifier loops, but at some point I have to convert them to the block form when I need to do something else.

I still commonly type

        return unless open my $fh, $file;

which I almost always have to rewrite in the same way because I want to put some other code in the unless() block (e.g. setting error variables, carping, etc.).

Subject and predicate

petdance on 2002-11-06T22:10:01

The reason I wrote it as
s/-/ /g for @array;
instead of
for ( @array ) {
    s/-/ /g;
}
was not to save keystrokes, but to put the interesting part of the code first. I think of how I'd say it in English:
Change any dashes to spaces throughout the list
instead of
Throughout the list, change any dashes to spaces
I think about that a lot. That's why I like the "open or die" metaphor instead of what I see as entirely backwards "die unless open".