Perl and operator SWITCH

As you may know Perl doesn’t contain a SWITCH control operator. Instead, there are many ways to create SWITCH. This is a good and bad. Yesterday I fixed a bug in our Billing System related with custom implementation of SWITCH operator. Image we have a code like that:
my $var1 = '';
my $var2 = '';
SWITCH: {
# the first option
$var1 = 11;
$var2 = 12;
last SWITCH if $type == 1;
# the second option
$var1 = 21;
$var2 = 22;
last SWITCH if $type == 2;
}

This example works fine if $type is 1 or 2. We suppose to have variables $var1 and $var2 empty in case $type is 3, for example. But they will be 21 and 22 accordingly. To avoid this mistake we should add the last option at the end of our SWITCH block:
$var1='';
$var2='';

Personally, I don’t like this implementation of SWITCH block. I prefer more clear and obvious way, IMHO:
my $var1 = '';
my $var2 = '';
SWITCH: for($type) {
/^1$/ && do { $var1 = 11; $var2 = 12; last SWITCH; };
/^2$/ && do { $var1 = 21; $var2 = 22; last SWITCH; };
}

In this case assignment will be done correctly.
Perl includes the module Switch.pm since version 5.8.0. This module implements the operator SWITCH in the same manner as other programming languages:
use Switch;
switch ($type) {
case 1 { $var1 = 11; $var2 = 12; }
case 2 { $var1 = 21; $var2 = 22; }
else { print "Note: [$type] is not triggered!" }
}

Well, it’s your decision to use the standard SWITCH operator or create your own. But be carefully, it can produce strange bugs.

Published by

Michael Stepanov

Site owner and admin :)

Leave a Reply

Your email address will not be published. Required fields are marked *