Seth Woolley's Man Viewer

Switch(3) - Switch - A switch statement for Perl - man 3 Switch

([section] manual, -k keyword, -K [section] search, -f whatis)
man plain no title

Switch(3)              Perl Programmers Reference Guide              Switch(3)



NAME
       Switch - A switch(1,n) statement for Perl

VERSION
       This document describes version(1,3,5) 2.10 of Switch, released Dec 29, 2003.

SYNOPSIS
               use Switch;

               switch(1,n) ($val) {

                       case 1          { print "number 1" }
                       case "a"        { print "string(3,n) a" }
                       case [1..10,42] { print "number in(1,8) list" }
                       case (@array)   { print "number in(1,8) list" }
                       case /\w+/      { print "pattern" }
                       case qr/\w+/    { print "pattern" }
                       case (%hash)    { print "entry in(1,8) hash" }
                       case (\%hash)   { print "entry in(1,8) hash" }
                       case (\&sub)    { print "arg to subroutine" }
                       else            { print "previous case not true" }
               }

BACKGROUND
       [Skip ahead to "DESCRIPTION" if(3,n) you don't care about the whys and
       wherefores of this control structure]

       In seeking to devise a "Swiss Army" case mechanism suitable for Perl,
       it is useful to generalize this notion of distributed conditional test-
       ing as far as possible. Specifically, the concept of "matching" between
       the switch(1,n) value and the various case values need not be restricted to
       numeric (or string(3,n) or referential) equality, as it is in(1,8) other lan-
       guages. Indeed, as Table 1 illustrates, Perl offers at least eighteen
       different ways in(1,8) which two values could generate a match.

               Table 1: Matching a switch(1,n) value ($s) with a case value ($c)

               Switch  Case    Type of Match Implied   Matching Code
               Value   Value
               ======  =====   =====================   =============

               number  same    numeric or referential  match if(3,n) $s == $c;
               or ref          equality

               object  method  result of method call   match if(3,n) $s->$c();
               ref     name                            match if(3,n) defined $s->$c();
                       or ref

               other   other   string(3,n) equality         match if(3,n) $s eq $c;
               non-ref non-ref
               scalar  scalar

               string(3,n)  regexp(3,n)  pattern match           match if(3,n) $s =~ /$c/;

               array   scalar  array entry existence   match if(3,n) 0<=$c && $c<@$s;
               ref             array entry definition  match if(3,n) defined $s->[$c];
                               array entry truth       match if(3,n) $s->[$c];

               array   array   array intersection      match if(3,n) intersects(@$s, @$c);
               ref     ref     (apply this table to
                                all pairs of elements
                                $s->[$i] and
                                $c->[$j])

               array   regexp(3,n)  array grep              match if(3,n) grep /$c/, @$s;
               ref

               hash    scalar  hash entry existence    match if(3,n) exists $s->{$c};
               ref             hash entry definition   match if(3,n) defined $s->{$c};
                               hash entry truth        match if(3,n) $s->{$c};

               hash    regexp(3,n)  hash grep               match if(3,n) grep /$c/, keys %$s;
               ref

               sub     scalar  return value defn       match if(3,n) defined $s->($c);
               ref             return value truth      match if(3,n) $s->($c);

               sub     array   return value defn       match if(3,n) defined $s->(@$c);
               ref     ref     return value truth      match if(3,n) $s->(@$c);

       In reality, Table 1 covers 31 alternatives, because only the equality
       and intersection tests are commutative; in(1,8) all other cases, the roles
       of the $s and $c variables could be reversed to produce a different
       test. For example, instead of testing a single hash for the existence
       of a series of keys ("match if(3,n) exists $s->{$c}"), one could test for
       the existence of a single key in(1,8) a series of hashes ("match if(3,n) exists
       $c->{$s}").

       As perltodo observes, a Perl case mechanism must support all these
       "ways to do it".

DESCRIPTION
       The Switch.pm module implements a generalized case mechanism that cov-
       ers the numerous possible combinations of switch(1,n) and case values
       described above.

       The module augments the standard Perl syntax with two new control
       statements: "switch(1,n)" and "case". The "switch(1,n)" statement takes a single
       scalar argument of any type, specified in(1,8) parentheses.  "switch(1,n)" stores
       this value as the current switch(1,n) value in(1,8) a (localized) control vari-
       able.  The value is followed by a block which may contain one or more
       Perl statements (including the "case" statement described below).  The
       block is unconditionally executed once the switch(1,n) value has been
       cached.

       A "case" statement takes a single scalar argument (in(1,8) mandatory paren-
       theses if(3,n) it's a variable; otherwise the parens are optional) and
       selects the appropriate type of matching between that argument and the
       current switch(1,n) value. The type of matching used is determined by the
       respective types of the switch(1,n) value and the "case" argument, as speci-
       fied in(1,8) Table 1. If the match is successful, the mandatory block asso-
       ciated with the "case" statement is executed.

       In most other respects, the "case" statement is semantically identical
       to an "if(3,n)" statement. For example, it can be followed by an "else"
       clause, and can be used as a postfix statement qualifier.

       However, when a "case" block has been executed control is automatically
       transferred to the statement after the immediately enclosing "switch(1,n)"
       block, rather than to the next statement within the block. In other
       words, the success of any "case" statement prevents other cases in(1,8) the
       same scope from executing. But see "Allowing fall-through" below.

       Together these two new statements provide a fully generalized case
       mechanism:

               use Switch;

               # AND LATER...

               %special = ( woohoo => 1,  d'oh => 1 );

               while (<>) {
                   switch(1,n) ($_) {

                       case (%special) { print "homer\n"; }      # if(3,n) $special{$_}
                       case /a-z/i     { print "alpha\n"; }      # if(3,n) $_ =~ /a-z/i
                       case [1..9]     { print "small num\n"; }  # if(3,n) $_ in(1,8) [1..9]

                       case { $_[0] >= 10 } {                    # if(3,n) $_ >= 10
                           my $age = <>;
                           switch(1,n) (sub{ $_[0] < $age } ) {

                               case 20  { print "teens\n"; }     # if(3,n) 20 < $age
                               case 30  { print "twenties\n"; }  # if(3,n) 30 < $age
                               else     { print "history(1,3,n,1 builtins)\n"; }
                           }
                       }

                       print "must be punctuation\n" case /\W/;  # if(3,n) $_ ~= /\W/
               }

       Note that "switch(1,n)"es can be nested within "case" (or any other) blocks,
       and a series of "case" statements can try different types of matches --
       hash membership, pattern match, array intersection, simple equality,
       etc. -- against the same switch(1,n) value.

       The use of intersection tests against an array reference is particu-
       larly useful for aggregating integral cases:

               sub classify_digit
               {
                       switch(1,n) ($_[0]) { case 0            { return 'zero' }
                                        case [2,4,6,8]    { return 'even' }
                                        case [1,3,4,7,9]  { return 'odd' }
                                        case /[A-F]/i     { return 'hex' }
                                      }
               }

       Allowing fall-through

       Fall-though (trying another case after one has already succeeded) is
       usually a Bad Idea in(1,8) a switch(1,n) statement. However, this is Perl, not a
       police state, so there is a way to do it, if(3,n) you must.

       If a "case" block executes an untargetted "next", control is immedi-
       ately transferred to the statement after the "case" statement (i.e.
       usually another case), rather than out of the surrounding "switch(1,n)"
       block.

       For example:

               switch(1,n) ($val) {
                       case 1      { handle_num_1(); next }    # and try next case...
                       case "1"    { handle_str_1(); next }    # and try next case...
                       case [0..9] { handle_num_any(); }       # and we're done
                       case /\d/   { handle_dig_any(); next }  # and try next case...
                       case /.*/   { handle_str_any(); next }  # and try next case...
               }

       If $val held the number 1, the above "switch(1,n)" block would call the
       first three "handle_..." subroutines, jumping to the next case test
       each time(1,2,n) it encountered a "next". After the thrid "case" block was
       executed, control would jump to the end of the enclosing "switch(1,n)"
       block.

       On the other hand, if(3,n) $val held 10, then only the last two "handle_..."
       subroutines would be called.

       Note that this mechanism allows the notion of conditional fall-through.
       For example:

               switch(1,n) ($val) {
                       case [0..9] { handle_num_any(); next if(3,n) $val < 7; }
                       case /\d/   { handle_dig_any(); }
               }

       If an untargetted "last" statement is executed in(1,8) a case block, this
       immediately transfers control out of the enclosing "switch(1,n)" block (in(1,8)
       other words, there is an implicit "last" at the end of each normal
       "case" block). Thus the previous example could also have been written:

               switch(1,n) ($val) {
                       case [0..9] { handle_num_any(); last if(3,n) $val >= 7; next; }
                       case /\d/   { handle_dig_any(); }
               }

       Automating fall-through

       In situations where case fall-through should be the norm, rather than
       an exception, an endless succession of terminal "next"s is tedious and
       ugly.  Hence, it is possible to reverse the default behaviour by speci-
       fying the string(3,n) "fallthrough" when importing the module. For example,
       the following code is equivalent to the first example in(1,8) "Allowing
       fall-through":

               use Switch 'fallthrough';

               switch(1,n) ($val) {
                       case 1      { handle_num_1(); }
                       case "1"    { handle_str_1(); }
                       case [0..9] { handle_num_any(); last }
                       case /\d/   { handle_dig_any(); }
                       case /.*/   { handle_str_any(); }
               }

       Note the explicit use of a "last" to preserve the non-fall-through be-
       haviour of the third case.

       Alternative syntax

       Perl 6 will provide a built-in switch(1,n) statement with essentially the
       same semantics as those offered by Switch.pm, but with a different pair
       of keywords. In Perl 6 "switch(1,n)" will be spelled "given", and "case"
       will be pronounced "when". In addition, the "when" statement will not
       require switch(1,n) or case values to be parenthesized.

       This future syntax is also (largely) available via the Switch.pm mod-
       ule, by importing it with the argument "Perl6".  For example:

               use Switch 'Perl6';

               given ($val) {
                       when 1       { handle_num_1(); }
                       when ($str1) { handle_str_1(); }
                       when [0..9]  { handle_num_any(); last }
                       when /\d/    { handle_dig_any(); }
                       when /.*/    { handle_str_any(); }
                       default      { handle anything else; }
               }

       Note that scalars still need to be parenthesized, since they would be
       ambiguous in(1,8) Perl 5.

       Note too that you can mix and match both syntaxes by importing the mod-
       ule with:

               use Switch 'Perl5', 'Perl6';

       Higher-order Operations

       One situation in(1,8) which "switch(1,n)" and "case" do not provide a good sub-
       stitute for a cascaded "if(3,n)", is where a switch(1,n) value needs to be tested
       against a series of conditions. For example:

               sub beverage {
                   switch(1,n) (shift) {

                       case sub { $_[0] < 10 }  { return 'milk' }
                       case sub { $_[0] < 20 }  { return 'coke' }
                       case sub { $_[0] < 30 }  { return 'beer' }
                       case sub { $_[0] < 40 }  { return 'wine(1,5)' }
                       case sub { $_[0] < 50 }  { return 'malt' }
                       case sub { $_[0] < 60 }  { return 'Moet' }
                       else                     { return 'milk' }
                   }
               }

       The need to specify each condition as a subroutine block is tiresome.
       To overcome this, when importing Switch.pm, a special "placeholder"
       subroutine named(5,8) "__" [sic] may also be imported. This subroutine con-
       verts (almost) any expression in(1,8) which it appears to a reference to a
       higher-order function. That is, the expression:

               use Switch '__';

               __ < 2 + __

       is equivalent to:

               sub { $_[0] < 2 + $_[1] }

       With "__", the previous ugly case statements can be rewritten:

               case  __ < 10  { return 'milk' }
               case  __ < 20  { return 'coke' }
               case  __ < 30  { return 'beer' }
               case  __ < 40  { return 'wine(1,5)' }
               case  __ < 50  { return 'malt' }
               case  __ < 60  { return 'Moet' }
               else           { return 'milk' }

       The "__" subroutine makes extensive use of operator overloading to per-
       form its magic. All operations involving __ are overloaded to produce
       an anonymous subroutine that implements a lazy version(1,3,5) of the original
       operation.

       The only problem is that operator overloading does not allow the
       boolean operators "&&" and "||" to be overloaded. So a case statement
       like this:

               case  0 <= __ && __ < 10  { return 'digit' }

       doesn't act as expected, because when it is executed, it constructs two
       higher order subroutines and then treats the two resulting references
       as arguments to "&&":

               sub { 0 <= $_[0] } && sub { $_[0] < 10 }

       This boolean expression is inevitably true, since both references are
       non-false. Fortunately, the overloaded 'bool' operator catches this
       situation and flags it as a error.

DEPENDENCIES
       The module is implemented using Filter::Util::Call and Text::Balanced
       and requires both these modules to be installed.

AUTHOR
       Damian Conway (damian@conway.org). The maintainer of this module is now
       Rafael Garcia-Suarez (rgarciasuarez@free.fr).

BUGS
       There are undoubtedly serious bugs lurking somewhere in(1,8) code this funky
       :-) Bug reports and other feedback are most welcome.

LIMITATIONS
       Due to the heuristic nature of Switch.pm's source parsing, the presence
       of regexes specified with raw(3x,7,8,3x cbreak) "?...?" delimiters may cause mysterious
       errors. The workaround is to use "m?...?" instead.

       Due to the way source filters work in(1,8) Perl, you can't use Switch inside
       an string(3,n) "eval".

       If your source file(1,n) is longer then 1 million characters and you have a
       switch(1,n) statement that crosses the 1 million (or 2 million, etc.)  char-
       acter boundary you will get mysterious errors. The workaround is to use
       smaller source files.

COPYRIGHT
           Copyright (c) 1997-2003, Damian Conway. All Rights Reserved.
           This module is free software. It may be used, redistributed
               and/or modified under the same terms as Perl itself.



perl v5.8.5                       2001-09-21                         Switch(3)

References for this manual (incoming links)