Codex

Switch

Section: User Contributed Perl Documentation (3pm)

Updated: 2014-09-23

Index?action=index Return to Main Contents


NAME

Switch - A switch statement for Perl, do not use if you can use given/when

SYNOPSIS

BACKGROUND

[Skip ahead to ``DESCRIPTION'' if 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 testing as far as possible. Specifically, the concept of ``matching between the switch value and the various case values need not be restricted to numeric (or string or referential) equality, as it is in other languages. Indeed, as Table 1 illustrates, Perl offers at least eighteen different ways in which two values could generate a match.

In reality, Table 1 covers 31 alternatives, because only the equality and intersection tests are commutative; in all other cases, the roles of the and 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 ( ), one could test for the existence of a single key in a series of hashes ( ).

DESCRIPTION

The Switch.pm module implements a generalized case mechanism that covers most (but not all) of the numerous possible combinations of switch and case values described above.

The module augments the standard Perl syntax with two new control statements: and . The statement takes a single scalar argument of any type, specified in parentheses. stores this value as the current switch value in a (localized) control variable. The value is followed by a block which may contain one or more Perl statements (including the statement described below). The block is unconditionally executed once the switch value has been cached.
A statement takes a single scalar argument (in mandatory parentheses if it's a variable; otherwise the parens are optional) and selects the appropriate type of matching between that argument and the current switch value. The type of matching used is determined by the respective types of the switch value and the argument, as specified in Table 1. If the match is successful, the mandatory block associated with the statement is executed.
In most other respects, the statement is semantically identical to an statement. For example, it can be followed by an clause, and can be used as a postfix statement qualifier.
However, when a block has been executed control is automatically transferred to the statement after the immediately enclosing block, rather than to the next statement within the block. In other words, the success of any statement prevents other cases in the same scope from executing. But see ``Allowing fall-through'' below.

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

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

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

Allowing fall-through

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

If a block executes an untargeted , control is immediately transferred to the statement after the statement (i.e. usually another case), rather than out of the surrounding block.

For example:

If held the number , the above block would call the first three subroutines, jumping to the next case test each time it encountered a . After the third block was executed, control would jump to the end of the enclosing block.
On the other hand, if held , then only the last two subroutines would be called.

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

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

Automating fall-through

In situations where case fall-through should be the norm, rather than an exception, an endless succession of terminal s is tedious and ugly. Hence, it is possible to reverse the default behaviour by specifying the string ``fallthrough when importing the module. For example, the following code is equivalent to the first example in ``Allowing fall-through:
Note the explicit use of a to preserve the non-fall-through behaviour of the third case.

Alternative syntax

Perl 6 will provide a built-in switch statement with essentially the same semantics as those offered by Switch.pm, but with a different pair of keywords. In Perl 6 will be spelled , and will be pronounced . In addition, the statement will not require switch or case values to be parenthesized.
This future syntax is also (largely) available via the Switch.pm module, by importing it with the argument . For example:

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

Note too that you can mix and match both syntaxes by importing the module with:

Higher-order Operations

One situation in which and do not provide a good substitute for a cascaded , is where a switch value needs to be tested against a series of conditions. For example:
(This is equivalent to writing , etc.; is the argument to the anonymous subroutine.)
The need to specify each condition as a subroutine block is tiresome. To overcome this, when importing Switch.pm, a special ``placeholder'' subroutine named [sic] may also be imported. This subroutine converts (almost) any expression in which it appears to a reference to a higher-order function. That is, the expression:

is equivalent to:

With , the previous ugly case statements can be rewritten:
The subroutine makes extensive use of operator overloading to perform its magic. All operations involving __ are overloaded to produce an anonymous subroutine that implements a lazy version 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:
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 :
This boolean expression is inevitably true, since both references are non-false. Fortunately, the overloaded operator catches this situation and flags it as an error.

DEPENDENCIES

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

AUTHOR

Damian Conway ([email protected]). This module is now maintained by Alexandr Ciornii ([email protected]). Previously was maintained by Rafael Garcia-Suarez and perl5 porters.

BUGS

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

May create syntax errors in other parts of code.

On perl 5.10.x may cause syntax error if ``case'' is present inside heredoc.

In general, use given/when instead. It were introduced in perl 5.10.0. Perl 5.10.0 was released in 2007.

LIMITATIONS

Due to the heuristic nature of Switch.pm's source parsing, the presence of regexes with embedded newlines that are specified with raw delimiters and don't have a modifier are indistinguishable from code chunks beginning with the division operator . As a workaround you must use or for such patterns. Also, the presence of regexes specified with raw delimiters may cause mysterious errors. The workaround is to use instead.
Due to the way source filters work in Perl, you can't use Switch inside an string .

May not work if sub prototypes are used (RT#33988).

Regex captures in when are not available to code.

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

COPYRIGHT


Index

NAME

SYNOPSIS

BACKGROUND

DESCRIPTION

Allowing fall-through

Automating fall-through

Alternative syntax

Higher-order Operations

DEPENDENCIES

AUTHOR

BUGS

LIMITATIONS

COPYRIGHT