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.