The given - when construct (know is other languages as case or switch)
can make the previous example musch more compact.
Perl compares the value of $operator (the topic) with each one of the values next to the when
keywords. When if finds one that fits the appropriate block is executed and perl jumps to the
next command after the given block.
If non of the when values fit the (optional) default block is evaluated.
Example 2-14. examples/scalars/calculator_given.p6
#!/usr/bin/perl6
print "Number:";
my $a = readline;
print "Operator: [+-*/]:";
my $operator = readline;
print "Number:";
my $b = readline;
given $operator {
when "+" { say $a + $b; }
when "-" { say $a - $b; }
when "*" { say $a * $b; }
when "/" { say $a / $b; }
default { say "Invalid operator $operator"; }
}
| Prev | Home (Copyright Gabor Szabo) Perl Training Israel | Next |
| Comparing values - Calculator | Up | String functions: index |