Perl‎ > ‎

Branching


if statement

if ($name eq 'Bob')
{
   say 'Hello, Bob!';
   found_bob();
}

if ($name eq 'Bob' && not greeted_bob())
{
   say 'Hello, Bob!';
   found_bob();
}


. . . though in this case, adding parentheses to the postfix conditional expression may add clarity, though the need to add parentheses
may argue against using the postfix form.

greet_bob() if ($name eq 'Bob' && not greeted_bob());

The unless directive is a negated form of if. Perl will evaluate the following statement when the conditional expression
evaluates to false:

say "You're no Bob!" unless $name eq 'Bob';

unless (is_leap_year() and is_full_moon())
{
   frolic();
   gambol();
}

sub frolic
{
   return unless @_;
   for my $chant (@_)
   {
      ...
   }
}

if ($name eq 'Bob')
{
   say 'Hi, Bob!';
   greet_user();
}
else
{
   say "I don't know you.";
   shun_user();
}

if ($name ne 'Bob')
{
   say "I don't know you.";
   shun_user();
}
else
{
   say 'Hi, Bob!';
   greet_user();
}

if ($name eq 'Bob')
{
   say 'Hi, Bob!';
   greet_user();
}
elsif ($name eq 'Jim')
{
   say 'Hi, Jim!';
   greet_user();
}
else
{
   say "You're not my uncle.";
   shun_user();
}

my $time_suffix = after_noon($time) ? 'morning' : 'afternoon';

say "Both true!" if ok(0, 'first subexpression')
                 && ok(1, 'second subexpression');




Comments