Typing foreach till the end

Four wasted keystrokes, or are they?


In Perl we have both for and foreach loops. One of them is just an alias to the other, so using the latter makes most sense when you are getting paid per keystroke. That's what I heard anyway.

Can't say I don't agree. Out of my utter laziness I've been skipping the each part lately. My current project shows 49 for loops and just one loop with an each. They do the same thing after all, right?

Right. But then I encountered this in my own code:

# check if the field exists
for my $name ($error->field) {
        croak "form does not contain a field definition for $name"
                if defined $name && !any { $_->name eq $name }
                @{$self->field_defs};
}

That got me thinking. Is this a bug? Did I forget to dereference field? Since it is a Moo field, it surely doesn't return a list. Was I sober?

No, that's just my way of writing:

{
        my $name = $error->field;
        ...
}

All you Perl haters out there, you think I don't know what my code does after some time? Of course I do! Just give me five minutes...

I needed a named variable, because it is used in three places, one of which is interpolated inside a string (so no method call allowed without leaving string), and the last one is inside any, which is basically a loop. Not using a named variable here hurts both readability and performance - repeated method calls are expensive :(

Creating this variable inside a new scope prevents possible name clashes with further code. This way you can use shorter names to embrace code golfing, without actually code golfing!

Jokes aside, I think using for to create a named variable inside a new scope is not that bad. The problem is now it looks like a loop with an error. That's where foreach enters the stage.

  • Need a named variable inside a new scope? Use for
  • Actually looping over multiple elements? Use foreach
  • Reading your code? The documentation is built-in!

That makes perfect sense! To me, at least. At 4 PM, today. Who knows what future holds?


Comments? Suggestions? Send to feedback@bbrtj.eu
Published on 2022-10-30