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