1Switch(3) User Contributed Perl Documentation Switch(3)
2
3
4
6 Switch - A switch statement for Perl
7
9 use Switch;
10
11 switch ($val) {
12 case 1 { print "number 1" }
13 case "a" { print "string a" }
14 case [1..10,42] { print "number in list" }
15 case (\@array) { print "number in list" }
16 case /\w+/ { print "pattern" }
17 case qr/\w+/ { print "pattern" }
18 case (\%hash) { print "entry in hash" }
19 case (\&sub) { print "arg to subroutine" }
20 else { print "previous case not true" }
21 }
22
24 [Skip ahead to "DESCRIPTION" if you don't care about the whys and
25 wherefores of this control structure]
26
27 In seeking to devise a "Swiss Army" case mechanism suitable for Perl,
28 it is useful to generalize this notion of distributed conditional
29 testing as far as possible. Specifically, the concept of "matching"
30 between the switch value and the various case values need not be
31 restricted to numeric (or string or referential) equality, as it is in
32 other languages. Indeed, as Table 1 illustrates, Perl offers at least
33 eighteen different ways in which two values could generate a match.
34
35 Table 1: Matching a switch value ($s) with a case value ($c)
36
37 Switch Case Type of Match Implied Matching Code
38 Value Value
39 ====== ===== ===================== =============
40
41 number same numeric or referential match if $s == $c;
42 or ref equality
43
44 object method result of method call match if $s->$c();
45 ref name match if defined $s->$c();
46 or ref
47
48 other other string equality match if $s eq $c;
49 non-ref non-ref
50 scalar scalar
51
52 string regexp pattern match match if $s =~ /$c/;
53
54 array scalar array entry existence match if 0<=$c && $c<@$s;
55 ref array entry definition match if defined $s->[$c];
56 array entry truth match if $s->[$c];
57
58 array array array intersection match if intersects(@$s, @$c);
59 ref ref (apply this table to
60 all pairs of elements
61 $s->[$i] and
62 $c->[$j])
63
64 array regexp array grep match if grep /$c/, @$s;
65 ref
66
67 hash scalar hash entry existence match if exists $s->{$c};
68 ref hash entry definition match if defined $s->{$c};
69 hash entry truth match if $s->{$c};
70
71 hash regexp hash grep match if grep /$c/, keys %$s;
72 ref
73
74 sub scalar return value defn match if defined $s->($c);
75 ref return value truth match if $s->($c);
76
77 sub array return value defn match if defined $s->(@$c);
78 ref ref return value truth match if $s->(@$c);
79
80 In reality, Table 1 covers 31 alternatives, because only the equality
81 and intersection tests are commutative; in all other cases, the roles
82 of the $s and $c variables could be reversed to produce a different
83 test. For example, instead of testing a single hash for the existence
84 of a series of keys ("match if exists $s->{$c}"), one could test for
85 the existence of a single key in a series of hashes ("match if exists
86 $c->{$s}").
87
89 The Switch.pm module implements a generalized case mechanism that
90 covers most (but not all) of the numerous possible combinations of
91 switch and case values described above.
92
93 The module augments the standard Perl syntax with two new control
94 statements: "switch" and "case". The "switch" statement takes a single
95 scalar argument of any type, specified in parentheses. "switch" stores
96 this value as the current switch value in a (localized) control
97 variable. The value is followed by a block which may contain one or
98 more Perl statements (including the "case" statement described below).
99 The block is unconditionally executed once the switch value has been
100 cached.
101
102 A "case" statement takes a single scalar argument (in mandatory
103 parentheses if it's a variable; otherwise the parens are optional) and
104 selects the appropriate type of matching between that argument and the
105 current switch value. The type of matching used is determined by the
106 respective types of the switch value and the "case" argument, as
107 specified in Table 1. If the match is successful, the mandatory block
108 associated with the "case" statement is executed.
109
110 In most other respects, the "case" statement is semantically identical
111 to an "if" statement. For example, it can be followed by an "else"
112 clause, and can be used as a postfix statement qualifier.
113
114 However, when a "case" block has been executed control is automatically
115 transferred to the statement after the immediately enclosing "switch"
116 block, rather than to the next statement within the block. In other
117 words, the success of any "case" statement prevents other cases in the
118 same scope from executing. But see "Allowing fall-through" below.
119
120 Together these two new statements provide a fully generalized case
121 mechanism:
122
123 use Switch;
124
125 # AND LATER...
126
127 %special = ( woohoo => 1, d'oh => 1 );
128
129 while (<>) {
130 chomp;
131 switch ($_) {
132 case (%special) { print "homer\n"; } # if $special{$_}
133 case /[a-z]/i { print "alpha\n"; } # if $_ =~ /a-z/i
134 case [1..9] { print "small num\n"; } # if $_ in [1..9]
135 case { $_[0] >= 10 } { print "big num\n"; } # if $_ >= 10
136 print "must be punctuation\n" case /\W/; # if $_ ~= /\W/
137 }
138 }
139
140 Note that "switch"es can be nested within "case" (or any other) blocks,
141 and a series of "case" statements can try different types of matches --
142 hash membership, pattern match, array intersection, simple equality,
143 etc. -- against the same switch value.
144
145 The use of intersection tests against an array reference is
146 particularly useful for aggregating integral cases:
147
148 sub classify_digit
149 {
150 switch ($_[0]) { case 0 { return 'zero' }
151 case [2,4,6,8] { return 'even' }
152 case [1,3,5,7,9] { return 'odd' }
153 case /[A-F]/i { return 'hex' }
154 }
155 }
156
157 Allowing fall-through
158 Fall-though (trying another case after one has already succeeded) is
159 usually a Bad Idea in a switch statement. However, this is Perl, not a
160 police state, so there is a way to do it, if you must.
161
162 If a "case" block executes an untargeted "next", control is immediately
163 transferred to the statement after the "case" statement (i.e. usually
164 another case), rather than out of the surrounding "switch" block.
165
166 For example:
167
168 switch ($val) {
169 case 1 { handle_num_1(); next } # and try next case...
170 case "1" { handle_str_1(); next } # and try next case...
171 case [0..9] { handle_num_any(); } # and we're done
172 case /\d/ { handle_dig_any(); next } # and try next case...
173 case /.*/ { handle_str_any(); next } # and try next case...
174 }
175
176 If $val held the number 1, the above "switch" block would call the
177 first three "handle_..." subroutines, jumping to the next case test
178 each time it encountered a "next". After the third "case" block was
179 executed, control would jump to the end of the enclosing "switch"
180 block.
181
182 On the other hand, if $val held 10, then only the last two "handle_..."
183 subroutines would be called.
184
185 Note that this mechanism allows the notion of conditional fall-through.
186 For example:
187
188 switch ($val) {
189 case [0..9] { handle_num_any(); next if $val < 7; }
190 case /\d/ { handle_dig_any(); }
191 }
192
193 If an untargeted "last" statement is executed in a case block, this
194 immediately transfers control out of the enclosing "switch" block (in
195 other words, there is an implicit "last" at the end of each normal
196 "case" block). Thus the previous example could also have been written:
197
198 switch ($val) {
199 case [0..9] { handle_num_any(); last if $val >= 7; next; }
200 case /\d/ { handle_dig_any(); }
201 }
202
203 Automating fall-through
204 In situations where case fall-through should be the norm, rather than
205 an exception, an endless succession of terminal "next"s is tedious and
206 ugly. Hence, it is possible to reverse the default behaviour by
207 specifying the string "fallthrough" when importing the module. For
208 example, the following code is equivalent to the first example in
209 "Allowing fall-through":
210
211 use Switch 'fallthrough';
212
213 switch ($val) {
214 case 1 { handle_num_1(); }
215 case "1" { handle_str_1(); }
216 case [0..9] { handle_num_any(); last }
217 case /\d/ { handle_dig_any(); }
218 case /.*/ { handle_str_any(); }
219 }
220
221 Note the explicit use of a "last" to preserve the non-fall-through
222 behaviour of the third case.
223
224 Alternative syntax
225 Perl 6 will provide a built-in switch statement with essentially the
226 same semantics as those offered by Switch.pm, but with a different pair
227 of keywords. In Perl 6 "switch" will be spelled "given", and "case"
228 will be pronounced "when". In addition, the "when" statement will not
229 require switch or case values to be parenthesized.
230
231 This future syntax is also (largely) available via the Switch.pm
232 module, by importing it with the argument "Perl6". For example:
233
234 use Switch 'Perl6';
235
236 given ($val) {
237 when 1 { handle_num_1(); }
238 when ($str1) { handle_str_1(); }
239 when [0..9] { handle_num_any(); last }
240 when /\d/ { handle_dig_any(); }
241 when /.*/ { handle_str_any(); }
242 default { handle anything else; }
243 }
244
245 Note that scalars still need to be parenthesized, since they would be
246 ambiguous in Perl 5.
247
248 Note too that you can mix and match both syntaxes by importing the
249 module with:
250
251 use Switch 'Perl5', 'Perl6';
252
253 Higher-order Operations
254 One situation in which "switch" and "case" do not provide a good
255 substitute for a cascaded "if", is where a switch value needs to be
256 tested against a series of conditions. For example:
257
258 sub beverage {
259 switch (shift) {
260 case { $_[0] < 10 } { return 'milk' }
261 case { $_[0] < 20 } { return 'coke' }
262 case { $_[0] < 30 } { return 'beer' }
263 case { $_[0] < 40 } { return 'wine' }
264 case { $_[0] < 50 } { return 'malt' }
265 case { $_[0] < 60 } { return 'Moet' }
266 else { return 'milk' }
267 }
268 }
269
270 (This is equivalent to writing "case (sub { $_[0] < 10 })", etc.; $_[0]
271 is the argument to the anonymous subroutine.)
272
273 The need to specify each condition as a subroutine block is tiresome.
274 To overcome this, when importing Switch.pm, a special "placeholder"
275 subroutine named "__" [sic] may also be imported. This subroutine
276 converts (almost) any expression in which it appears to a reference to
277 a higher-order function. That is, the expression:
278
279 use Switch '__';
280
281 __ < 2
282
283 is equivalent to:
284
285 sub { $_[0] < 2 }
286
287 With "__", the previous ugly case statements can be rewritten:
288
289 case __ < 10 { return 'milk' }
290 case __ < 20 { return 'coke' }
291 case __ < 30 { return 'beer' }
292 case __ < 40 { return 'wine' }
293 case __ < 50 { return 'malt' }
294 case __ < 60 { return 'Moet' }
295 else { return 'milk' }
296
297 The "__" subroutine makes extensive use of operator overloading to
298 perform its magic. All operations involving __ are overloaded to
299 produce an anonymous subroutine that implements a lazy version of the
300 original operation.
301
302 The only problem is that operator overloading does not allow the
303 boolean operators "&&" and "||" to be overloaded. So a case statement
304 like this:
305
306 case 0 <= __ && __ < 10 { return 'digit' }
307
308 doesn't act as expected, because when it is executed, it constructs two
309 higher order subroutines and then treats the two resulting references
310 as arguments to "&&":
311
312 sub { 0 <= $_[0] } && sub { $_[0] < 10 }
313
314 This boolean expression is inevitably true, since both references are
315 non-false. Fortunately, the overloaded 'bool' operator catches this
316 situation and flags it as an error.
317
319 The module is implemented using Filter::Util::Call and Text::Balanced
320 and requires both these modules to be installed.
321
323 Damian Conway (damian@conway.org). This module is now maintained by
324 Rafael Garcia-Suarez (rgarciasuarez@gmail.com) and more generally by
325 the Perl 5 Porters (perl5-porters@perl.org), as part of the Perl core.
326
328 There are undoubtedly serious bugs lurking somewhere in code this funky
329 :-) Bug reports and other feedback are most welcome.
330
332 Due to the heuristic nature of Switch.pm's source parsing, the presence
333 of regexes with embedded newlines that are specified with raw "/.../"
334 delimiters and don't have a modifier "//x" are indistinguishable from
335 code chunks beginning with the division operator "/". As a workaround
336 you must use "m/.../" or "m?...?" for such patterns. Also, the presence
337 of regexes specified with raw "?...?" delimiters may cause mysterious
338 errors. The workaround is to use "m?...?" instead.
339
340 Due to the way source filters work in Perl, you can't use Switch inside
341 an string "eval".
342
343 If your source file is longer then 1 million characters and you have a
344 switch statement that crosses the 1 million (or 2 million, etc.)
345 character boundary you will get mysterious errors. The workaround is to
346 use smaller source files.
347
349 Copyright (c) 1997-2008, Damian Conway. All Rights Reserved.
350 This module is free software. It may be used, redistributed
351 and/or modified under the same terms as Perl itself.
352
353
354
355perl v5.16.3 2014-06-10 Switch(3)