1Switch(3pm)            Perl Programmers Reference Guide            Switch(3pm)
2
3
4

NAME

6       Switch - A switch statement for Perl
7

VERSION

9       This document describes version 2.14 of Switch, released Dec 29, 2008.
10

SYNOPSIS

12           use Switch;
13
14           switch ($val) {
15               case 1          { print "number 1" }
16               case "a"        { print "string a" }
17               case [1..10,42] { print "number in list" }
18               case (\@array)  { print "number in list" }
19               case /\w+/      { print "pattern" }
20               case qr/\w+/    { print "pattern" }
21               case (\%hash)   { print "entry in hash" }
22               case (\&sub)    { print "arg to subroutine" }
23               else            { print "previous case not true" }
24           }
25

BACKGROUND

27       [Skip ahead to "DESCRIPTION" if you don't care about the whys and
28       wherefores of this control structure]
29
30       In seeking to devise a "Swiss Army" case mechanism suitable for Perl,
31       it is useful to generalize this notion of distributed conditional
32       testing as far as possible. Specifically, the concept of "matching"
33       between the switch value and the various case values need not be
34       restricted to numeric (or string or referential) equality, as it is in
35       other languages. Indeed, as Table 1 illustrates, Perl offers at least
36       eighteen different ways in which two values could generate a match.
37
38               Table 1: Matching a switch value ($s) with a case value ($c)
39
40               Switch  Case    Type of Match Implied   Matching Code
41               Value   Value
42               ======  =====   =====================   =============
43
44               number  same    numeric or referential  match if $s == $c;
45               or ref          equality
46
47               object  method  result of method call   match if $s->$c();
48               ref     name                            match if defined $s->$c();
49                       or ref
50
51               other   other   string equality         match if $s eq $c;
52               non-ref non-ref
53               scalar  scalar
54
55               string  regexp  pattern match           match if $s =~ /$c/;
56
57               array   scalar  array entry existence   match if 0<=$c && $c<@$s;
58               ref             array entry definition  match if defined $s->[$c];
59                               array entry truth       match if $s->[$c];
60
61               array   array   array intersection      match if intersects(@$s, @$c);
62               ref     ref     (apply this table to
63                                all pairs of elements
64                                $s->[$i] and
65                                $c->[$j])
66
67               array   regexp  array grep              match if grep /$c/, @$s;
68               ref
69
70               hash    scalar  hash entry existence    match if exists $s->{$c};
71               ref             hash entry definition   match if defined $s->{$c};
72                               hash entry truth        match if $s->{$c};
73
74               hash    regexp  hash grep               match if grep /$c/, keys %$s;
75               ref
76
77               sub     scalar  return value defn       match if defined $s->($c);
78               ref             return value truth      match if $s->($c);
79
80               sub     array   return value defn       match if defined $s->(@$c);
81               ref     ref     return value truth      match if $s->(@$c);
82
83       In reality, Table 1 covers 31 alternatives, because only the equality
84       and intersection tests are commutative; in all other cases, the roles
85       of the $s and $c variables could be reversed to produce a different
86       test. For example, instead of testing a single hash for the existence
87       of a series of keys ("match if exists $s->{$c}"), one could test for
88       the existence of a single key in a series of hashes ("match if exists
89       $c->{$s}").
90

DESCRIPTION

92       The Switch.pm module implements a generalized case mechanism that
93       covers most (but not all) of the numerous possible combinations of
94       switch and case values described above.
95
96       The module augments the standard Perl syntax with two new control
97       statements: "switch" and "case". The "switch" statement takes a single
98       scalar argument of any type, specified in parentheses.  "switch" stores
99       this value as the current switch value in a (localized) control
100       variable.  The value is followed by a block which may contain one or
101       more Perl statements (including the "case" statement described below).
102       The block is unconditionally executed once the switch value has been
103       cached.
104
105       A "case" statement takes a single scalar argument (in mandatory
106       parentheses if it's a variable; otherwise the parens are optional) and
107       selects the appropriate type of matching between that argument and the
108       current switch value. The type of matching used is determined by the
109       respective types of the switch value and the "case" argument, as
110       specified in Table 1. If the match is successful, the mandatory block
111       associated with the "case" statement is executed.
112
113       In most other respects, the "case" statement is semantically identical
114       to an "if" statement. For example, it can be followed by an "else"
115       clause, and can be used as a postfix statement qualifier.
116
117       However, when a "case" block has been executed control is automatically
118       transferred to the statement after the immediately enclosing "switch"
119       block, rather than to the next statement within the block. In other
120       words, the success of any "case" statement prevents other cases in the
121       same scope from executing. But see "Allowing fall-through" below.
122
123       Together these two new statements provide a fully generalized case
124       mechanism:
125
126               use Switch;
127
128               # AND LATER...
129
130               %special = ( woohoo => 1,  d'oh => 1 );
131
132               while (<>) {
133                   chomp;
134                   switch ($_) {
135                       case (%special) { print "homer\n"; }      # if $special{$_}
136                       case /[a-z]/i   { print "alpha\n"; }      # if $_ =~ /a-z/i
137                       case [1..9]     { print "small num\n"; }  # if $_ in [1..9]
138                       case { $_[0] >= 10 } { print "big num\n"; } # if $_ >= 10
139                       print "must be punctuation\n" case /\W/;  # if $_ ~= /\W/
140                   }
141               }
142
143       Note that "switch"es can be nested within "case" (or any other) blocks,
144       and a series of "case" statements can try different types of matches --
145       hash membership, pattern match, array intersection, simple equality,
146       etc. -- against the same switch value.
147
148       The use of intersection tests against an array reference is
149       particularly useful for aggregating integral cases:
150
151               sub classify_digit
152               {
153                       switch ($_[0]) { case 0            { return 'zero' }
154                                        case [2,4,6,8]    { return 'even' }
155                                        case [1,3,5,7,9]  { return 'odd' }
156                                        case /[A-F]/i     { return 'hex' }
157                                      }
158               }
159
160   Allowing fall-through
161       Fall-though (trying another case after one has already succeeded) is
162       usually a Bad Idea in a switch statement. However, this is Perl, not a
163       police state, so there is a way to do it, if you must.
164
165       If a "case" block executes an untargeted "next", control is immediately
166       transferred to the statement after the "case" statement (i.e. usually
167       another case), rather than out of the surrounding "switch" block.
168
169       For example:
170
171               switch ($val) {
172                       case 1      { handle_num_1(); next }    # and try next case...
173                       case "1"    { handle_str_1(); next }    # and try next case...
174                       case [0..9] { handle_num_any(); }       # and we're done
175                       case /\d/   { handle_dig_any(); next }  # and try next case...
176                       case /.*/   { handle_str_any(); next }  # and try next case...
177               }
178
179       If $val held the number 1, the above "switch" block would call the
180       first three "handle_..." subroutines, jumping to the next case test
181       each time it encountered a "next". After the third "case" block was
182       executed, control would jump to the end of the enclosing "switch"
183       block.
184
185       On the other hand, if $val held 10, then only the last two "handle_..."
186       subroutines would be called.
187
188       Note that this mechanism allows the notion of conditional fall-through.
189       For example:
190
191               switch ($val) {
192                       case [0..9] { handle_num_any(); next if $val < 7; }
193                       case /\d/   { handle_dig_any(); }
194               }
195
196       If an untargeted "last" statement is executed in a case block, this
197       immediately transfers control out of the enclosing "switch" block (in
198       other words, there is an implicit "last" at the end of each normal
199       "case" block). Thus the previous example could also have been written:
200
201               switch ($val) {
202                       case [0..9] { handle_num_any(); last if $val >= 7; next; }
203                       case /\d/   { handle_dig_any(); }
204               }
205
206   Automating fall-through
207       In situations where case fall-through should be the norm, rather than
208       an exception, an endless succession of terminal "next"s is tedious and
209       ugly.  Hence, it is possible to reverse the default behaviour by
210       specifying the string "fallthrough" when importing the module. For
211       example, the following code is equivalent to the first example in
212       "Allowing fall-through":
213
214               use Switch 'fallthrough';
215
216               switch ($val) {
217                       case 1      { handle_num_1(); }
218                       case "1"    { handle_str_1(); }
219                       case [0..9] { handle_num_any(); last }
220                       case /\d/   { handle_dig_any(); }
221                       case /.*/   { handle_str_any(); }
222               }
223
224       Note the explicit use of a "last" to preserve the non-fall-through
225       behaviour of the third case.
226
227   Alternative syntax
228       Perl 6 will provide a built-in switch statement with essentially the
229       same semantics as those offered by Switch.pm, but with a different pair
230       of keywords. In Perl 6 "switch" will be spelled "given", and "case"
231       will be pronounced "when". In addition, the "when" statement will not
232       require switch or case values to be parenthesized.
233
234       This future syntax is also (largely) available via the Switch.pm
235       module, by importing it with the argument "Perl6".  For example:
236
237               use Switch 'Perl6';
238
239               given ($val) {
240                       when 1       { handle_num_1(); }
241                       when ($str1) { handle_str_1(); }
242                       when [0..9]  { handle_num_any(); last }
243                       when /\d/    { handle_dig_any(); }
244                       when /.*/    { handle_str_any(); }
245                       default      { handle anything else; }
246               }
247
248       Note that scalars still need to be parenthesized, since they would be
249       ambiguous in Perl 5.
250
251       Note too that you can mix and match both syntaxes by importing the
252       module with:
253
254               use Switch 'Perl5', 'Perl6';
255
256   Higher-order Operations
257       One situation in which "switch" and "case" do not provide a good
258       substitute for a cascaded "if", is where a switch value needs to be
259       tested against a series of conditions. For example:
260
261               sub beverage {
262                   switch (shift) {
263                       case { $_[0] < 10 } { return 'milk' }
264                       case { $_[0] < 20 } { return 'coke' }
265                       case { $_[0] < 30 } { return 'beer' }
266                       case { $_[0] < 40 } { return 'wine' }
267                       case { $_[0] < 50 } { return 'malt' }
268                       case { $_[0] < 60 } { return 'Moet' }
269                       else                { return 'milk' }
270                   }
271               }
272
273       (This is equivalent to writing "case (sub { $_[0] < 10 })", etc.; $_[0]
274       is the argument to the anonymous subroutine.)
275
276       The need to specify each condition as a subroutine block is tiresome.
277       To overcome this, when importing Switch.pm, a special "placeholder"
278       subroutine named "__" [sic] may also be imported. This subroutine
279       converts (almost) any expression in which it appears to a reference to
280       a higher-order function. That is, the expression:
281
282               use Switch '__';
283
284               __ < 2
285
286       is equivalent to:
287
288               sub { $_[0] < 2 }
289
290       With "__", the previous ugly case statements can be rewritten:
291
292               case  __ < 10  { return 'milk' }
293               case  __ < 20  { return 'coke' }
294               case  __ < 30  { return 'beer' }
295               case  __ < 40  { return 'wine' }
296               case  __ < 50  { return 'malt' }
297               case  __ < 60  { return 'Moet' }
298               else           { return 'milk' }
299
300       The "__" subroutine makes extensive use of operator overloading to
301       perform its magic. All operations involving __ are overloaded to
302       produce an anonymous subroutine that implements a lazy version of the
303       original operation.
304
305       The only problem is that operator overloading does not allow the
306       boolean operators "&&" and "||" to be overloaded. So a case statement
307       like this:
308
309               case  0 <= __ && __ < 10  { return 'digit' }
310
311       doesn't act as expected, because when it is executed, it constructs two
312       higher order subroutines and then treats the two resulting references
313       as arguments to "&&":
314
315               sub { 0 <= $_[0] } && sub { $_[0] < 10 }
316
317       This boolean expression is inevitably true, since both references are
318       non-false. Fortunately, the overloaded 'bool' operator catches this
319       situation and flags it as an error.
320

DEPENDENCIES

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

AUTHOR

326       Damian Conway (damian@conway.org). This module is now maintained by
327       Rafael Garcia-Suarez (rgarciasuarez@gmail.com) and more generally by
328       the Perl 5 Porters (perl5-porters@perl.org), as part of the Perl core.
329

BUGS

331       There are undoubtedly serious bugs lurking somewhere in code this funky
332       :-) Bug reports and other feedback are most welcome.
333

LIMITATIONS

335       Due to the heuristic nature of Switch.pm's source parsing, the presence
336       of regexes with embedded newlines that are specified with raw "/.../"
337       delimiters and don't have a modifier "//x" are indistinguishable from
338       code chunks beginning with the division operator "/". As a workaround
339       you must use "m/.../" or "m?...?" for such patterns. Also, the presence
340       of regexes specified with raw "?...?" delimiters may cause mysterious
341       errors. The workaround is to use "m?...?" instead.
342
343       Due to the way source filters work in Perl, you can't use Switch inside
344       an string "eval".
345
346       If your source file is longer then 1 million characters and you have a
347       switch statement that crosses the 1 million (or 2 million, etc.)
348       character boundary you will get mysterious errors. The workaround is to
349       use smaller source files.
350
352           Copyright (c) 1997-2008, Damian Conway. All Rights Reserved.
353           This module is free software. It may be used, redistributed
354               and/or modified under the same terms as Perl itself.
355
356
357
358perl v5.10.1                      2009-03-30                       Switch(3pm)
Impressum