The Perl language includes a number of ways to implement branching. Choosing a method is a matter of preference. Usually the decision is made based on which method generates the most succinct or readable code. The major decision making key-words in Perl are if and unless. The if statement works similar to if statements in other languages. It tests if a condition is true, and executes code only if it is. The unless statement uses the same syntax as the if statement, but it executes code only if the condition is false. The following example demonstrates uses for both statements:
#!/usr/bin/perl
my $order=“cookies”; my %cookies=( “butter” => 0.5, “sugar” => 1, “eggs” => 1, “baking soda” => 0.5, “flour” => 1.5, “chocolate chips” => 1 ); my %inventory=( “butter” => 1, “sugar” => 1, “flour” => 1, “eggs” => 1 );
sub buy { my ($i) = @_; print “I need to buy more $i.\n”; $inventory{$i} = 10; }
# Basic if statement with an else my $recipe; if ($order eq “cookies”) { print “I will bake cookies.\n”; $recipe=\%cookies; } else { die “I only know how to bake cookies.\n”; }
for my $i (keys %$recipe) { # unless and if statements preceded by an action buy($i) unless (exists $inventory{$i}); buy($i) if ($inventory{$i} < %$recipe{$i}); }
# Basic unless statement my $oven=“off”; unless ($oven eq “on”) { print “Turning on the oven…\n”; $oven=“on”; }
print “Mixing all the ingredients…\n”; print “Baking…\n”;
# Basic if statement with not if (not $oven eq “off”) { print “Turning off the oven…\n”; $oven=“off”; }
print “The $order came out great!\n”; |
The first if statement in this example is an if-else with syntax similar to other languages. If there were more conditions in the chain, the keyword ‘elsif’ would be used for them. The next examples demonstrate a different Perl syntax for conditions. If there is only one action to perform, it can precede the if or unless keywords. The next example shows an unless statement with no else. In Perl, unless is equivalent to if (not …) so the last example could also be done with unless.