Is there any way to run a block of code if none of the case blocks were matched? For instance:
switch($a) {
case // {}
case // {}
...
# DO SOMETHING IF NONE OF THE ABOVE CASES WERE MATCHED
}
else
is not what I'm looking for, since it applies only to the last case block.
Perl does not support the use of switch statements. A switch statement allows a variable to be tested against a set list of values. In Perl, the equivalent of the switch statement is the given-when syntax.
The value is followed by a block, which may contain one or more case statement followed by a block of Perl statement(s). A case statement takes a single scalar argument and selects the appropriate type of matching between the case argument and the current switch value.
In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.
There's always the switching in Perl 5.10, if you're running it of course.
use feature qw(switch);
given($a){
when(1) { print 'Number one'; }
when(2) { print 'Number two'; }
default { print 'Everything else' }
}
Please note that use Switch
in any form is deprecated as it is being replaced (and removed in the next perl release) by perl's own form of switch statement, which is, as already answered:
use feature qw(switch);
given ($x)
{
when ('case1') { print 1; }
default {print 0; }
}
Using default case achieves the outcome you want. Also don't forget to use last
if you want the switch to stop being evaluated after one condition is evaluated true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With