Multiway branches in Perl - the given and when syntax
Archive - Originally posted on "The Horse's Mouth" - 2010-09-22 06:19:01 - Graham Ellis
But in the Perl 6 spec, and added as a back-implemented feature in the current Perl 5 releases, is the given ... when structure. In this, you establish the variable / expression on which you want to test (you "topicalise it") in the given clause, and you then add a whole series of when clauses, each of which contains *something* to match the topicalised value against. Let's see an example:
given (uc($pc)) {
when ("") {
say ("You didn't enter anything"); }
when (/^[A-Z]{1,2}[0-9][0-9A-Z]?\s+\d[A-Z]{2}$/) {
say ("That's the format for a British postcode"); }
when ...
You'll see that once again, the Perl team lead by Larry Wall has come up with something that's very neat and clever and much more practical than a conventional switch. You'll note that there is NOT a break statement added to the baggage of each of the conditional code blocks to prevent it falling through to the next section. And you'll note that my when clause can contain a string or a regular expression. Actually that's just the tip of the iceberg - Perl's when clause is using the new intelligent match operator ~~ which works out what to match depending on the context in which it is used ... and the right half of context is set within the when clause by the the type of data in the brackets. The first one tests:
($_ ~~ "")
notes
• If your multiple way branch (code as if - elsif) would have required a final safety net to catch anything that didn't match and of the cases, you would have used an else. With given, the equivalent is a default clause:
default {
say ("Not one of the regular formats we know");
}
• If - unusually - you do want the code to drop through and continue testing cases, even if you've found one that's true, you can use a continue. Please note that continues to test - it does not drop into the next case and perform that irrespective of whether that next match worked as would happen with C's switch.
• There's a full piece of code showing what I've talked about [here] - matching specific postcodes and particular patterns (and a rare chance to include places like Tristan da Cunha on our web site!).
P.S. - The three way point isn't strictly correct as an illustration ... I should really have used a "ladder" of single points ...