Jump to content

Perl Programming/Keywords/when

From Wikibooks, open books for an open world
Previous: warn Keywords Next: while

The when keyword

[edit | edit source]

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 | edit source]
  EXPRESSION when EXPRESSION
  when EXPRESSION

Examples

[edit | edit source]
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 | edit source]
Previous: warn Keywords Next: while