Perl Programming/Keywords/when

Previous: warn Keywords Next: while

The when keyword edit

when is a flow-control keyword that is used in the for and given statements.

The form EXPRESSION when EXPRESSION is used in the for statement, the form when EXPRESSION in the given statement that is similar to the C switch statement.

Please consider that given is considered highly experimental!

Syntax edit

  EXPRESSION when EXPRESSION
  when EXPRESSION

Examples edit

use v5.14;

for ($var) {
  $abc = 1 when /^abcd/;
  $def = 1 when /^efgh/;
  $xyz = 1 when /^wxyz/;
  default { $nothing = 1 }
}
}}
use v5.10.1;

given ($var) {
  when (/^abc/) { $abc = 1 }
  when (/^def/) { $def = 1 }
  when (/^xyz/) { $xyz = 1 }
  default       { $nothing = 1 }
}
}}
use v5.14;

given ($var) {
  $abc = 1 when /^abc/;
  $def = 1 when /^def/;
  $xyz = 1 when /^xyz/;
  default { $nothing = 1 }
}
}}

See also edit

Previous: warn Keywords Next: while