Learning Perl - Conditional Statements


Learning Perl - Conditional Statements


So far we have covered basic variables in Perl, today we are going to look at how to use these variables in conditional statements.

A conditional statement in programming is a statement that executes a block of code based on whether a condition is true or false. In Perl, we can use 'if', 'elsif', 'else' and 'unless' to create conditional statements.

The most basic conditional in Perl is the 'if' statement. It allows you to execute a block of code only if a certain condition is true. You can then chain multiple conditions using 'elsif' and provide a default action using 'else'.

When you want to check a condition, you can use comparison operators like '==' for numeric comparison or 'eq' for string comparison, essentially the code that is within the condition must return either true or false.

You can use the following table as a reference of operators that can be used in conditions when comparing scalars:

Operator Description Example
== Numeric equality $a == $b
!= Numeric inequality $a != $b
< Less than $a < $b
> Greater than $a > $b
<= Less than or equal to $a <= $b
>= Greater than or equal to $a >= $b
eq String equality $a eq $b
ne String inequality $a ne $b
lt String less than $a lt $b
gt String greater than $a gt $b
le String less or equal $a le $b
ge String greater or equal $a ge $b
defined Check if variable is defined defined $var
exists Check if hash key exists exists $hash{$key}
&& Logical AND $a && $b
and Logical AND (lower precedence) $a and $b
// Defined or $a // $b
or Logical OR (lower precedence) $a or $b
! Logical NOT !$a

Today we will create a few simple Perl scripts that checks the value of a command line input and prints different messages based on its value. First create a file named 'conditional.pl' and add the following code:

#!/usr/bin/perl
use strict;
use warnings;
my $value = shift;
if ($value < 5) {
    print "Value is less than 5\n";
} elsif ($value == 10) {
    print "Value is equal to 10\n";
} else {
    print "Value is greater than 5 and not equal to 10\n";
}
Enter fullscreen mode Exit fullscreen mode

Save the file and run it using the command:

perl conditional.pl 10
Enter fullscreen mode Exit fullscreen mode

The output should be:

Value is equal to 10
Enter fullscreen mode Exit fullscreen mode

We have created a variable '$value' that takes an input from the command line, we receive the input by using 'shift' to remove the first argument from the stack. We will talk more about the stack in a future post. The script then checks if the value is less than 5, equal to 10, or greater than 5 and not equal to 10. We use the '<' less than operator to check if the value is less than 5, '==' to check if it is equal to 10, and the else statement to handle all other cases.

You can also use string comparisons in a similar way. For example, if you want to check if a string variable is equal to another string, you can use the eq operator. Here’s an example:

#!/usr/bin/perl
use strict;
use warnings;
my $name = shift;
if ($name eq "Alice") {
    print "Hello, Alice!\n";
} elsif ($name eq "Bob") {
    print "Hello, Bob!\n";
} else {
    print "Hello, stranger!\n";
}
Enter fullscreen mode Exit fullscreen mode

Save this code in a file named 'string_conditional.pl' and run it with:

perl string_conditional.pl Alice
Enter fullscreen mode Exit fullscreen mode

You should see the output:

Hello, Alice!
Enter fullscreen mode Exit fullscreen mode

If you change the input to "Bob" or any other name, the script will respond accordingly.

You can also use logical operators to combine conditions. For example, if you want to check if a number is between two values, you can do something like this:

#!/usr/bin/perl
use strict;
use warnings;
my $number = shift;
if ($number >= 1 && $number <= 10) {
    print "Number is between 1 and 10\n";
} elsif ($number > 10 && $number <= 20) {
    print "Number is between 11 and 20\n";
} else {
    print "Number is outside the range of 1 to 20\n";
}
Enter fullscreen mode Exit fullscreen mode

Save this code in a file named 'range_conditional.pl' and run it with:

perl range_conditional.pl 15
Enter fullscreen mode Exit fullscreen mode

You should see the output:

Number is between 11 and 20
Enter fullscreen mode Exit fullscreen mode

Another conditional statement that can be used in Perl is 'unless', which is the opposite of 'if'. It executes a block of code only if the condition is false. Here’s an example:

#!/usr/bin/perl
use strict;
use warnings;
my $age = shift;
unless ($age >= 18) {
    print "You are not old enough to vote.\n";
} else {
    print "You are old enough to vote.\n";
}
Enter fullscreen mode Exit fullscreen mode

Save this code in a file named 'unless_conditional.pl' and run it with:

perl unless_conditional.pl 16
Enter fullscreen mode Exit fullscreen mode

You should see the output:

You are old enough to vote.
Enter fullscreen mode Exit fullscreen mode

You can also chain elsif and else statements to handle multiple conditions. Here’s a more complex example:

#!/usr/bin/perl
use strict;
use warnings;
my $score = shift;
unless(defined $score) {
    print "No score provided.\n";
} elsif ($score < 50) {
    print "You failed the test.\n";
} elsif ($score < 75) {
    print "You passed the test.\n";
} else {
    print "You excelled in the test!\n";
}
Enter fullscreen mode Exit fullscreen mode

Save this code in a file named defined_conditional.pl and run it with:

perl defined_conditional.pl 85
Enter fullscreen mode Exit fullscreen mode

You should see the output:

You excelled in the test!
Enter fullscreen mode Exit fullscreen mode

That concludes our post today, we have covered the basics of conditional statements in Perl. In the next post we will look at loops, which will allow us to repeat actions based on conditions.

Related Blogs

Learning Perl – Introduction
Perl has long been known as the “duct tape of the Internet,” or "the Swiss Army chainsaw of scripting...
Learning Perl - Variables
I will attempt to explain things in this post in a way that is easy to understand, even for those who...
Learning Perl - Arrays
As stated in the previous post, Perl has three types of variables: scalars, arrays and hashes. Today...
Learning Perl - Hashes
In the last post we covered the basics of arrays, today we will look at hashes in more detail. What...
Learning Perl - Loops and Iteration
In previous posts, we explored variables, arrays, hashes, and conditional statements in Perl. Now...
Learning Perl - Scalars
Before moving onto more complex topics lets come back to how we represent data in Perl. The most...
Learning Perl - References
In the last post we learnt how to create a reference to a scalar, an array, and a hash. In this post,...
Learning Perl - Ternary Operators
In a previous post, we learned about conditional statements in Perl. The ternary operator is an...
Learning Perl - Subroutines
Subroutines are one of the most important building blocks in programming. They allow you to organise...
Learning Perl - Regular Expressions
Regular expressions also known as regex or regexp, are a powerful way to match patterns in text. Most...
Learning Perl - Modules
A module in Perl is a reusable piece of code that can be included in your scripts to provide...
Learning Perl - CPAN
In the last post I showed you how to create a new module and how to use it in your code. In this post...
Learning Perl - Plain Old Documentation
When you write and program in any language it is good practice to document your code. Each language...
Learning Perl - Testing
In this post we will look at how to test Perl code using the Test::More module. Like documentation,...
Learning Perl - Exporting
In programming, we often want to share functionality across different parts of our code. In Perl,...
Learning Perl - Object Orientation
Object-Oriented Programming (OOP) is a widely used programming paradigm that enables the creation of...
Learning Perl - Inheritance
In the last post we discussed Object Oriented Programming in Perl, focusing on the basics of creating...
Learning Perl - File Handles
In programming file processing is a key skill to master. Files are essential for storing data,...
Learning Perl - Prototypes
Today we are going to discuss Perl subroutine prototypes, which are a way to enforce a certain...
Learning Perl - Overloading Operators
In the last post we investigated prototype subroutines in Perl. In this post, we will look at...