Switch in Perl

Here’s the Perl translation of the given code example:

Switch Statements in Perl

Switch statements express conditionals across many branches.

use strict;
use warnings;
use Time::Piece;

# Here's a basic switch.
my $i = 2;
print "Write $i as ";
given ($i) {
    when (1) { say "one"; }
    when (2) { say "two"; }
    when (3) { say "three"; }
}

# You can use commas to separate multiple expressions in the same case statement. We use the optional default case in this example as well.
my $weekday = localtime->wday;
given ($weekday) {
    when (0) { say "It's the weekend"; }
    when (6) { say "It's the weekend"; }
    default { say "It's a weekday"; }
}

# Switch without an expression is an alternate way to express if/else logic. Here we also show how the case expressions can be non-constants.
my $hour = localtime->hour;
given () {
    when ($hour < 12) { say "It's before noon"; }
    default           { say "It's after noon"; }
}

# A type switch compares types instead of values. You can use this to discover the type of an interface value. In this example, the variable $t will have the type corresponding to its clause.
sub whatAmI {
    my $i = shift;
    given (ref($i) || $i) {
        when ('SCALAR') { say "I'm a scalar"; }
        when ('ARRAY')  { say "I'm an array"; }
        when ('HASH')   { say "I'm a hash"; }
        when ('CODE')   { say "I'm a code reference"; }
        default         { printf "Don't know type %s\n", ref($i) || $i; }
    }
}

whatAmI(\"true");
whatAmI([1]);
whatAmI({"key" => "value"});

To run the program, save the code in switch.pl and use Perl to execute it.

$ perl switch.pl
Write 2 as two
It's a weekday
It's after noon
I'm a scalar
I'm an array
I'm a hash

In Perl, given-when is a way to express switch-like logic, but remember that it’s an experimental feature and you need to use the feature pragma. This method is very handy for cases where traditional if-else statements would be too verbose.