Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Switch Statement

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.

like image 276
snoofkin Avatar asked Feb 07 '11 08:02

snoofkin


People also ask

Does Perl have a switch statement?

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.

Does Perl have a case statement?

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.

What is a switch () statement?

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.


2 Answers

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' }
}
like image 51
chambwez Avatar answered Nov 14 '22 03:11

chambwez


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.

like image 42
cyber-guard Avatar answered Nov 14 '22 02:11

cyber-guard