Paleolithic Perl Case Structures
During its first 20 years of existence, Perl had no official switch
or case statement. Prior to the appearance of given in the v5.10 release, people would
craft their own case structures using a bare block or a once-through
foreach loop. Here’s one
example:
SWITCH: {
if (/^abc/) { $abc = 1; last SWITCH }
if (/^def/) { $def = 1; last SWITCH }
if (/^xyz/) { $xyz = 1; last SWITCH }
$nothing = 1;
}and here’s another:
SWITCH: {
/^abc/ && do { $abc = 1; last SWITCH };
/^def/ && do { $def = 1; last SWITCH };
/^xyz/ && do { $xyz = 1; last SWITCH };
$nothing = 1;
}or even just:
if (/^abc/) { $abc = 1 }
elsif (/^def/) { $def = 1 }
elsif (/^xyz/) { $xyz = 1 }
else { $nothing = 1 }In this next example, notice how the last operators conveniently ignore the
do {} blocks, which aren’t loops,
and exit the main loop instead:
for ($very_nasty_long_name[$i++][$j++]–>method()) {
/this pattern/ and do { push @flags, "–e"; last };
/that one/ and do { push @flags, "–h"; last };
/something else/ and do { last };
die "unknown value: '$_'";
}You’ll see that idiom from time to time in older Perl code,
since for was the only way to write
a decent topicalizer until given
showed up.
Regardless of which topicalizer you use, specifying the value only once on repeated compares is much easier to type and, therefore, harder to mistype. It avoids possible side effects from evaluating the expression again.
Cascading use of the ?: operator can also work for simple cases. Here we again use ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access