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