Switch(3)

Switch(3) πŸ’…

User Contributed Perl Documentation β€” okay bestie, we're in the Switch(3) manual page and it's giving "useful but also a little cursed" energy. Buckle up πŸŽ€

πŸ‘‘ NAME πŸ‘‘

Switch β€” a switch statement for Perl. Do not use if you can use given/when β€” like, seriously bestie, that's the whole name and the whole warning. No cap.


πŸŽ€ SYNOPSIS πŸŽ€

So here's the vibe. You use Switch; and then you write a switch block like this β€” exactly this:

use Switch;

switch ($val) {
    case 1          { print "number 1" }
    case "a"        { print "string a" }
    case [1..10,42] { print "number in list" }
    case (\@array)  { print "number in list" }
    case /\w+/      { print "pattern" }
    case qr/\w+/    { print "pattern" }
    case (\%hash)   { print "entry in hash" }
    case (\&sub)    { print "arg to subroutine" }
    else            { print "previous case not true" }
}

It's giving classic Perl switch realness. Iconic. Slightly ancient. We move. πŸ¦‹


πŸŒ€ BACKGROUND πŸŒ€

[Skip ahead to "DESCRIPTION" if you don't care about the whys and wherefores of this control structure] β€” honestly valid, bestie πŸ’…

So the whole quest here is to devise a "Swiss Army" case mechanism suitable for Perl, and 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 does not need to be restricted to numeric (or string or referential) equality, like it is in other languages. Not even close, bestie.

Indeed, as Table 1 illustrates, Perl offers at least eighteen different ways in which two values could generate a match. Eighteen. The range. πŸ’€

🌸 Table 1: Matching a switch value ($s) with a case value ($c) 🌸

  • Switch value: number or ref; case value: same β€” numeric or referential equality. Matching code: match if $s == $c;
  • Switch value: object ref; case value: method name or ref β€” result of method call. Matching code:
    • match if $s->$c();
    • match if defined $s->$c();
  • Switch value: other non-ref scalar; case value: other non-ref scalar β€” string equality. Matching code: match if $s eq $c;
  • Switch value: string; case value: regexp β€” pattern match. Matching code: match if $s =~ /$c/;
  • Switch value: array ref; case value: scalar β€” array stuff. Matching code:
    • array entry existence β€” match if 0<=$c && $c<@$s;
    • array entry definition β€” match if defined $s->[$c];
    • array entry truth β€” match if $s->[$c];
  • Switch value: array ref; case value: array ref β€” array intersection (apply this table to all pairs of elements $s->[$i] and $c->[$j]). Matching code: match if intersects(@$s, @$c);
  • Switch value: array ref; case value: regexp β€” array grep. Matching code: match if grep /$c/, @$s;
  • Switch value: hash ref; case value: scalar β€” hash stuff. Matching code:
    • hash entry existence β€” match if exists $s->{$c};
    • hash entry definition β€” match if defined $s->{$c};
    • hash entry truth β€” match if $s->{$c};
  • Switch value: hash ref; case value: regexp β€” hash grep. Matching code: match if grep /$c/, keys %$s;
  • Switch value: sub ref; case value: scalar β€” return value stuff. Matching code:
    • return value defn β€” match if defined $s->($c);
    • return value truth β€” match if $s->($c);
  • Switch value: sub ref; case value: array ref β€” return value stuff. Matching code:
    • return value defn β€” match if defined $s->(@$c);
    • return value truth β€” match if $s->(@$c);

In reality, Table 1 covers 31 alternatives, because only the equality and intersection tests are commutative. In all other cases, the roles of the $s and $c 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 (match if exists $s->{$c}), one could test for the existence of a single key in a series of hashes (match if exists $c->{$s}). Mind blown, lowkey. 🀯

Anyway, that's the background tea β€” the next part picks up with DESCRIPTION, and it's gonna be useful, bestie. 🌈

✨ DESCRIPTION ✨

So here's the tea: Switch.pm implements a generalized case mechanism, and it covers most (but like, not all β€” read the fine print bestie) of the numerous possible combos of switch and case values described up above.

The module augments standard Perl syntax with two brand new control statements: switch and case.

The switch statement takes a single scalar argument of any type, specified in parentheses. switch stores this value as the current switch value in a (localized) control variable. That value is followed by a block, and that block may contain one or more Perl statements (including the case statement described below). The block is unconditionally executed once the switch value has been cached. 🫢

A case 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 case argument, as specified in Table 1. If the match is successful, the mandatory block associated with the case statement is executed. ✨

In most other respects, the case statement is semantically identical to an if statement. For example, it can be followed by an else clause, and can be used as a postfix statement qualifier. Love that for us.

But β€” and this is the moment, pay attention β€” when a case block has been executed, control is automatically transferred to the statement after the immediately enclosing switch block, rather than to the next statement within the block. In other words, the success of any case 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:

        use Switch;

        # AND LATER...

        %special = ( woohoo => 1,  d'oh => 1 );

        while (<>) {
            chomp;
            switch ($_) {
                case (%special) { print "homer\n"; }      # if $special{$_}
                case /[a-z]/i   { print "alpha\n"; }      # if $_ =~ /a-z/i
                case [1..9]     { print "small num\n"; }  # if $_ in [1..9]
                case { $_[0] >= 10 } { print "big num\n"; } # if $_ >= 10
                print "must be punctuation\n" case /\W/;  # if $_ ~= /\W/
            }
        }

Note that switches can be nested within case (or any other) blocks, and a series of case statements can try different types of matches β€” hash membership, pattern match, array intersection, simple equality, etc. β€” against the same switch value. It's giving versatility, honestly. πŸ’…

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

        sub classify_digit
        {
                switch ($_[0]) { case 0            { return 'zero' }
                                 case [2,4,6,8]    { return 'even' }
                                 case [1,3,5,7,9]  { return 'odd' }
                                 case /[A-F]/i     { return 'hex' }
                               }
        }

🌈 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 case block executes an untargeted next, control is immediately transferred to the statement after the case statement (i.e. usually another case), rather than out of the surrounding switch block.

For example:

        switch ($val) {
                case 1      { handle_num_1(); next }    # and try next case...
                case "1"    { handle_str_1(); next }    # and try next case...
                case [0..9] { handle_num_any(); }       # and we're done
                case /\d/   { handle_dig_any(); next }  # and try next case...
                case /.*/   { handle_str_any(); next }  # and try next case...
        }

If $val held the number 1, the above switch block would call the first three handle_... subroutines, jumping to the next case test each time it encountered a next. After the third case block was executed, control would jump to the end of the enclosing switch block.

On the other hand, if $val held 10, then only the last two handle_... subroutines would be called. See how that works? 🧚

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

        switch ($val) {
                case [0..9] { handle_num_any(); next if $val < 7; }
                case /\d/   { handle_dig_any(); }
        }

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

        switch ($val) {
                case [0..9] { handle_num_any(); last if $val >= 7; next; }
                case /\d/   { handle_dig_any(); }
        }

πŸ¦‹ Automating fall-through

In situations where case fall-through should be the norm, rather than an exception, an endless succession of terminal nexts 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":

        use Switch 'fallthrough';

        switch ($val) {
                case 1      { handle_num_1(); }
                case "1"    { handle_str_1(); }
                case [0..9] { handle_num_any(); last }
                case /\d/   { handle_dig_any(); }
                case /.*/   { handle_str_any(); }
        }

Note the explicit use of a last to preserve the non-fall-through behaviour of the third case. Don't forget it, bestie, or you'll be falling through forever πŸ’€

πŸ’œ 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 switch will be spelled given, and case will be pronounced when. In addition, the when 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 Perl6. For example:

        use Switch 'Perl6';

        given ($val) {
                when 1       { handle_num_1(); }
                when ($str1) { handle_str_1(); }
                when [0..9]  { handle_num_any(); last }
                when /\d/    { handle_dig_any(); }
                when /.*/    { handle_str_any(); }
                default      { handle anything else; }
        }

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

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

        use Switch 'Perl5', 'Perl6';

πŸ‘‘ Higher-order Operations

One situation in which switch and case do not provide a good substitute for a cascaded if, is where a switch value needs to be tested against a series of conditions. For example:

        sub beverage {
            switch (shift) {
                case { $_[0] < 10 } { return 'milk' }
                case { $_[0] < 20 } { return 'coke' }
                case { $_[0] < 30 } { return 'beer' }
                case { $_[0] < 40 } { return 'wine' }
                case { $_[0] < 50 } { return 'malt' }
                case { $_[0] < 60 } { return 'Moet' }
                else                { return 'milk' }
            }
        }

(This is equivalent to writing case (sub { $_[0] < 10 }), etc.; $_[0] 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:

        use Switch '__';

        __ < 2

is equivalent to:

        sub { $_[0] < 2 }

With __, the previous ugly case statements can be rewritten:

        case  __ < 10  { return 'milk' }
        case  __ < 20  { return 'coke' }
        case  __ < 30  { return 'beer' }
        case  __ < 40  { return 'wine' }
        case  __ < 50  { return 'malt' }
        case  __ < 60  { return 'Moet' }
        else           { return 'milk' }

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. Witchcraft? No, just Perl πŸ”₯

⚠️ The only problem is that operator overloading does not allow the boolean operators && and || to be overloaded. So a case statement like this:
        case  0 <= __ && __ < 10  { return 'digit' }

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 &&:

        sub { 0 <= $_[0] } && sub { $_[0] < 10 }

This boolean expression is inevitably true, since both references are non-false. Fortunately, the overloaded 'bool' operator catches this situation and flags it as an error. So like… it'll yell at you instead of silently lying. Small mercies 😭


πŸŽ€ DEPENDENCIES πŸŽ€

The module is implemented using Filter::Util::Call and Text::Balanced and requires both these modules to be installed. Yes, both. Install them. πŸ’…


🌸 AUTHOR 🌸

Damian Conway (damian@conway.org). This module is now maintained by Alexandr Ciornii (alexchorny@gmail.com). Previously was maintained by Rafael Garcia-Suarez and perl5 porters. Shoutout to the whole lineage honestly 🫢


πŸ’€ 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.

⚠️ Fr fr, that last bit is the realest advice on this whole page β€” the module itself is telling you to use given/when instead. Listen to it πŸ™ˆ

πŸ’€ LIMITATIONS πŸ’€

Okay bestie, gather round, because this is the part where Switch.pm is a little extra 😭. Its source parsing is heuristic, and that means some stuff can trip it up in truly mysterious ways.

  • Because of the heuristic nature of Switch.pm's source parsing, regexes with embedded newlines that are specified with raw /.../ delimiters and don't have a modifier //x are indistinguishable from code chunks beginning with the division operator /. The workaround? You must use m/.../ or m?...? for those patterns. Slay, but make it explicit πŸ’….
  • Also, regexes specified with raw ?...? delimiters may cause mysterious errors πŸ‘€. The workaround is to use m?...? instead.
  • Due to the way source filters work in Perl, you can't use Switch inside a string eval. Not me trying to nest vibes that do not nest πŸ™ˆ.
  • 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.

Legal bit, bestie β€” I'm not gonna freestyle this one, because copyright and license text is literally not the place for creative liberties 🫢. Here's the exact text:

    Copyright (c) 1997-2008, Damian Conway. All Rights Reserved.
    This module is free software. It may be used, redistributed
        and/or modified under the same terms as Perl itself.

And that's the whole page, bestie! The footer says this is from perl v5.42.0, dated 2014-09-15, and it's the Switch(3) manpage β€” iconic, periodt πŸ’–βœ¨πŸ¦‹

πŸ“¦ where this page comes from