given Statement
Perl given
statement, is similar to the switch case statement in other
languages.
The given
statement works like a series of if statements that allow you to
match an expression or variable against different values, depending on the
matched value, Perl will execute statements in the corresponding when
clause.
Perl introduced the given
statement since version 5.10. In order to use the
Perl given
statement, you must use the following pragma:
use v5.10;
Or use the following pragma:
use feature "switch";
There are several new keywords introduced along with the given
such as:
when
, break
and continue
.
given (expr) {
when (expr1) { statement; }
when (expr1) { statement; }
when (expr1) { statement; }
...
}
|
The following program asks the user to input an RGB (red, green, blue) color and returns its color code:
use v5.10; # at least for Perl 5.10
#use feature "switch";
use warnings;
use strict;
my $color;
my $code;
print("Please enter a RGB color to get its code:\n");
$color = <STDIN>;
chomp($color);
$color = uc($color);
given($color){
when ('RED') { $code = '#FF0000'; }
when ('GREEN') { $code = '#00FF00'; }
when ('BLUE') { $code = '#0000FF'; }
default {
$code = '';
}
}
if ($code ne '') {
print("code of $color is $code \n");
} else {
print("$color is not RGB color\n");
}
From Perl version 5.12, you can use the when
statement as a statement
modifier like the following example:
given ($color) {
$code = '#FF0000' when 'RED';
$code = '#00FF00' when 'GREEN';
$code = '#0000FF' when 'BLUE';
default { $code = ''; }
}
In addition, the given statement returns a value that is the result of the last expression.
print do {
given ($color) {
"#FF0000\n" when 'RED';
"#00FF00\n" when 'GREEN';
"#0000FF\n" when 'BLUE';
default { ''; }
}
}
More complex example:
use v5.12;
use strict;
use warnings;
print 'Enter something: ';
chomp( my $input = <> );
print do {
given ($input) {
"The input has numbers\n" when /\d/;
"The input has letters\n" when /[a-zA-Z]/;
default { "The input has neither number nor letter\n"; }
}
}