Lesson 02 – Conditional

If you want to do something based on a certain criteria, you should use a conditional.

#!/usr/bin/perl

use strict;
use warnings;

my $pizza = "pepperoni";

if ($pizza eq "pepperoni")
{
     print "Yes, my pizza is pepperoni!\n";
}
elsif ($pizza eq "plain")
{
     print "Plain pizza is good too.\n";
}
else
{
     print "I don't want it.\n";
}

The eq operator checks if the two strings match.

If you are dealing with numbers, you should be using one of these numeric comparison operators:

  • == checks whether two numbers are equal
  • > checks whether the first number is greater than the second number
  • >= checks whether the first number is greater than or equal to the second number
  • < checks whether the first number is less than the second number
  • <= checks whether the first number is less than or equal to the second number
  • != checks whether the first number is not equal to the second number
  • <=> is the sort comparison operator 1 is returned if the first number is greater than the second number. 0 is returned if the first number is equal to the second number. -1 is returned if the first number is less than the second number.

When using simple expressions, you can use the postfix form (also called the statement modifier) which looks something like this:

print "I like pepperoni pizza." if $pizza eq "pepperoni";

Notice how it doesn’t require any curly braces for the postfix form.

unless (defined($pizza))
{
    print "Tell me what kind of pizza you want.\n";
}

The conditional means the same thing as “if $pizza is not defined”.

if (!defined($pizza))
{
    print "Tell me what kind of pizza you want.\n";
}

The ternary conditional operator is the same as using if and else. It looks like this:

$pizza eq "pepperoni" ? print "I like pepperoni pizza." : print "I don\'t want anything else.";

given/when is equivalent to an if/elsif chain

given ($pizza)
{
when "pepperoni" { print "Yes, my pizza is pepperoni!\n"; }
when "plain" { print "Plain pizza is good too.\n"; }
default { print "I don't want it.\n"; }
}

If you’re familiar with other programming languages like C, given/when is basically switch/case spelled differently.

Notes: expression of ‘given’ is in scalar context, and always assigns to $_ (topic variable).

$_ is available in that block of code. It has lexical scope.

‘when’ is actually not required in a ‘given’ block. It’s simply a way of quickly testing a value by assigning it to $_

given/when does an implicit smart match

given (whatever()) { when (10) { ... } }

when (10) is implicitly when ($_ ~~ 10)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>