Perl Switch Statement

snoofkin picture snoofkin · Feb 7, 2011 · Viewed 53.8k times · Source

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.

Answer

chambwez picture chambwez · Feb 7, 2011

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' }
}