Perl switch Statement



Perl switch statement is another opportunity to write the conditional statements in Perl.

In this free short tutorial I want to tell you how to handle the situations when you want to write a multiway branch statement without using a long basic if-elsif-else pattern.

You’ll find out several interesting ways to replace the cascaded ifs by the switch pattern and you’ll learn some useful techniques that you can use in your conditional statements.



Please have a look at the next simple pseudo code:

if(variable == 1) {
  statement_1";
} elsif(variable == 2) {
  statement_2";
} elsif(variable == 3) {
  statement_3";
} else {
  default_statement";
}

If our variable has the value 1, the script program will execute the statement_1, if it has the value 2, it will execute the statement_2, if it has the value 3, it will execute the statement_3 and if the value is neither 1 nor 2 or 3, the program will execute the default_statement.

In some languages like PHP or C, there is the switch statement that let you rewrite the above pseudo code as follows:

switch(variable) {
  case 1:
    statement_1";      
    break;
  case 2:
    statement_2";
    break;
  case 3:
    statement_3";
    break;
  default:
      default_statement;
}

Here break is used to leave the Perl switch statement and continue with the code that follows the switch statement. If you omit a break statement, the program will fall-through the next condition, allowing you to handle multiple cases.

Now that you know the meaning of the switch statement, the bad news is that there is no Perl switch/case statement in the versions prior to 5.8.x, because of the huge variety of tests available: numerical and string comparisons, regexp matching, overloaded comparisons and so on.

The good news is that you can:

  1. easily emulate or build it if you work in an earlier version of Perl (prior to 5.8.x)
  2. use the Switch module if you work in Perl 5.8.x or
  3. use the given/when (instead of switch/case) statement if you work in Perl 5.10 version
Based on a Perl 6 proposal, with Perl 5.10 this very complex statement was finally added, but the given/when statement is way more powerful than a C switch/case statement and that’s probably why it appeared so late in the core of Perl language.

In the following I’ll review each of these three opportunities.


1. How to emulate the switch statement

1.1. You can use a bare block in order to construct a case structure that looks syntactically similar with the switch statement found in other languages. We’ll label our block with the noun SWITCH and because a bare block is a loop that executes only once, we can use the last, next and redo loop controls inside. Our compound Perl switch statement could look as follows:

$var = 2;
SWITCH: {
  $var == 1 && do { print "\$var = 1\n"; last SWITCH; };
  $var == 2 && do { print "\$var = 2\n"; last SWITCH; };
  $var == 3 && do { print "\$var = 3\n"; last SWITCH; };
  print "\$var is not equal with 1 or 2 or 3\n";
}
# the output displays $var = 2

In the syntax form used above, we can omit even the label SWITCH. The last control will immediately end the execution of the block and will jump at the following statement after the block (labeled or not). Please note that the last control ignores the do block which is not a loop and exits from the SWITCH block instead. Inside the switch block, on each line the $var is first evaluated and if the left condition is true, the script will execute the corresponding do block.

1.2. Next I’ll mention another sample of emulated Perl switch statement that uses the corresponding form of if as a modifier, inside a while loop:

print "Gess the colours:\n";
LINE: while() {
  SWITCH: { 
    $color = "blue", last SWITCH if /blue/i; 
    $color = "white", last SWITCH if /white/i; 
    $color = "red", last SWITCH if /red/i; 
    print "Try again\n"; next LINE;
  } 
  print "color = $color\n";
}

This code will read a line of text from the standard input stream and if one of the words (blue, white or red) matches, it will display the word; otherwise it will display the text "Try again" and the script program will continue by reading another line of text. If you want to test this code, in order to exit from the while loop you must type the Ctrl/Z in Windows or Ctrl/d in Linux characters followed by Enter. Please note the using of the case insensitively regexp match operator here.

1.3. Another alternative is to use the foreach statement (or its for equivalent name) as in the following construct:

# assign a string value to a scalar variable
$choice = "blue";
SWITCH: foreach($choice) {
  /blue/i  && do { print "Colour is blue\n"; last SWITCH;};  
  /yellow/i  && do { print "Colour is yellow\n"; last SWITCH;}; 
  /green/i  && do { print "Colour is green\n"; last SWITCH;};    
  die "Unknown colour: $choice \n"; 
}
# it displays: Colour is blue

Click here to watch a video on youtube where you can see a complete example.

1.4. A totally different approach for emulating a Perl switch structure is to use a hash table like in the next example snippet code:

# initialize some hash structure
%fruitsColors = (
  "apple"  => "red",
  "banana" => "yellow",
  "orange" => "orange",
  "plum"   => "dark blue"
);

print "Fruit: ";
chomp($fruit = );
$color = $fruitsColors {lc $fruit} || "unknown";
print "The $fruit has the colour $color\n";

In this way, the string lookup runs very fast. This code:
  • will read from stdin a word representing the name of a fruit
  • will discard the trailing newline of the word (by applying the builtin chomp function)
  • next, it will look up in the %fruitsColors hash for the fruit name and if it finds it, will store the given color of the fruit in the $color scalar variable, otherwise the $color variable will be initialized with the text "unknown"
  • finally, the result of the search will be printed
In the hash structure you can use an unlimited number of entries, the disadvantage of this method is that you can’t search for a match like in one of the previous example, but only for a specific entry item (like apple, banana, and so on). You must also keep in mind that if the hashtable is too big, Perl will allocate a lot of memory to store its (key, value) pair elements.


2. How to use the Perl Switch module.

This module was made available beginning with the 5.8.x version of Perl and covers a lot of possible combinations of switch having as single input argument (in a scalar context) a number, a string, a specific pattern, a reference to an array or a hash (associative array), or a call to a subroutine. Like the switch from the C language, the Perl Switch module allows you the use of fall-through – i.e. trying another case after one that has already succeeded.

Now this module was included in the Perl core distribution, but if you have an older version of Perl it’s possible that this module is not included (in this case if you want to use the Perl Switch module you need to install it - on a Windows platform, if you installed ActiveState’s ActivePerl, you can run their Perl Package Manager from your command shell - or upgrade your Perl version). For a full description of all its features, you can locate this module by searching at CPAN after the word 'switch' and learn more ways to invoke it.

The next simple script sample shows you one of the way through which you can use the Perl Switch module in your Perl programs or applications:

use Switch;

$i;
chomp($var=);

switch ($var){
  case(1) { $i = "One"; }
  case(2) { $i = "Two"; }
  case(3) { $i = "Three"; }
  else    { $i = "Other"; }
}

print "case: $i\n";

Note that you can mix and match both syntax formats (switch and given) if you use the declaration:

use Switch 'Perl5', 'Perl6';

3. How to Use switch in Perl 5.10

Based on the Perl 6 proposal, starting from Perl 5.10 is enabled a new switch feature. This Perl switch statement is spelled given, and case is pronounced when. The using of the given/when statement is very similar (there are minor differences) with the Perl switch/case statement. For instance, the Perl switch statement from the previous example can be rewritten as follows:

given ($var){
  when(1) { $i = "One"; }
  when(2) { $i = "Two"; }
  when(3) { $i = "Three"; }
  default { $i = "Other"; }
}



Table of Contents:

A Perl Script
Install Perl
Running Perl
Perl Data Types
Perl Variables
Perl Operators
Perl Lists
Perl Arrays
    Array Size
    Array Length
Perl Hashes
Perl Statements
    Perl if
    Perl unless
    Perl while
    Perl do-while
    Perl until
    Perl do-until
    Perl for
    Perl foreach
Built-in Perl Functions
    Functions by Category
        String Functions
        Regular Expressions and Pattern Matching
        List Functions
        Array Functions
        Hash Functions
        Miscellaneous Functions
    Functions in alphabetical order
        chomp
        chop
        chr
        crypt
        defined
        delete
        each
        exists
        grep
        hex
        index
        join
        keys
        lc
        lcfirst
        length
        map
        oct
        ord
        pack
        pop
        push
        q
        qq
        qw
        reverse
        rindex
        scalar
        shift
        sort
        splice
        split
        sprintf
        substr
        tr
        uc
        ucfirst
        undef
        unpack
        unshift
        values

return from Perl switch to Perl Basics



Would you like to create your own website like this one?
Hit the Alarm Clock!

Site Build It!