Conditional statements in Perl

Similar to the rest of the Perl language, we will have similarities with bash scripting and some completely new ways of implementing conditions. This will often work in our favor; thus, making the code more readable.

Replacing command line lists

First, we do not have the command line list logic, which we use in bash and we do not make use of the && and ||. Instead of these rather weird looking symbols, the conditional logic for single statements in Perl is written in the following manner:

exit(2) if scalar @ARGV < 1;
print("Hello $ARGV[0]
") unless scalar @ARGV == 0;

In the first example, we exit with an error code of 2, if we have supplied less than one command-line argument. The bash equivalent to this will be:

[ $# -lt 1 ] && exit 2

In the second example, we will only print the hello statement if we have supplied arguments. This will be written in bash, as shown in the following example:

[ $# -eq 0 ] || echo "Hello $1"

Personally, I like Perl; the way as it at least uses words, so we may understand what is happening even if we have not come across the symbols before.

If and unless

Within Perl, as we have already seen in the previous examples, we can make use of negative logic using unless. We both have the traditional if keyword and now unless is an addition. We can use these in our short code, as we have seen or in complete blocks of code.

We can edit the existing args.pl to create a new file: $HOME/bin/ifargs.pl. The file should read similar to the following code:

#!/usr/bin/perl
use English;
print("You are using $PROGRAM_NAME
");
my $count = scalar @ARGV;
if ($count > 0) {
  print("You have supplied $count arguments
");
  print("Hello $ARGV[0]
");
}

The code now has an additional argument, which we have declared and set with the line that reads my $count = scalar @ARGV;. We used this value as a condition for the if statement. The block of code constrained in the brace brackets will execute only if the condition is true.

We demonstrate the running of this program with and without arguments in the following screenshot:

If and unless

We can write a similar code using unless:

print("You are using $PROGRAM_NAME
");
my $count = scalar @ARGV;
unless ($count == 0) {
  print("You have supplied $count arguments
");
  print("Hello $ARGV[0]
");

}

The code in the brackets now runs only if the condition is false. In this case, if we have not supplied arguments, the code will not run.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.7.240