Scoping out an even conciser fork idiom
Years ago I wrote about a concise fork
idiom. It turns out that it’s possible to do better than everything I discussed in that entry as well as the proposals in the comments.
I didn’t at the time appreciate a clever aspect of variable scoping in Perl:
use strict;
sub get_answer { 0 }
if ( my $answer = get_answer ) {
...;
} else {
print $answer;
}
This compiles and works as intended. In other words, a variable declared within an if
or elsif
conditional is in scope not just in that branch, but in all following branches (and elsif
conditionals) as well. Which means it is possible to write the following:
if ( my $kid = fork ) {
print "parent of $kid\n";
} elsif ( defined $kid ) {
print "child of ", getppid, "\n";
} else {
die "Couldn't fork: $!\n";
}
It doesn’t get more low-key than this.
I am sure there are many similar applications of the same idea in other scenarios that I missed over the years, for which instead I awkwardly declared a variable in a separate statement up front because I thought that that was necessary in order to refer to it from several branches of an if/else chain. Not so.
Don't feel bad. I've been forgetting that one every few years since before the camel book was published. That's just one of the perils of coding in multiple languages, you keep having to relearn a nuance or two every so often.
I do in fact not feel bad at all, I’m just posting this because if I missed this then I’m sure a lot of other people have as well, even at my level of expertise in Perl.
And though I’ve always appreciated just how right Perl got its lexical scoping design, it pleasantly surprised me to find it even righter still than I already appreciated. For all the idiosyncrasies to outright warts that Perl’s design inherited from its deep Unix toolbox lineage, in this particular aspect the design is just standout excellent and right – and every time I’ve grasped something new about it (which hadn’t occurred in a very long time now), this has only been confirmed further. What may well be my favorite aspect of Perl’s design turned out to be even better than I already knew.