< Perl Programming < Keywords

The when keyword

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

  EXPRESSION when EXPRESSION
  when EXPRESSION

Examples

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

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.