GNU/Linux Programmer's Solver - Conditionals in Perl

Guess program in Perl. Conditionals, if, switch and constants
PROGRAMMING GUESS Perl
#!/usr/bin/perl
$n= 42;

print "Guess what number I'm thinking of? ";
$v = <>;
die "Only positive numbers" if $v < 0;

if ($v == $n) {
    print "Well Done!\n";
}
else {
    print "Keep Trying!.\n";
    print "The number is " . (($v < $n) ? "HIGHER" : "LOWER") . "\n";

    # If we've failed, we add a hint
    print "Hint: ";
    $h = abs ($v - $n);
    if    ($h < 5)  {print " TOO HOT!!!\n"} # ; optional in this case
    elsif ($h < 10) {print " HOT\n";}
    elsif ($h < 15) {print " WARM\n";}
    else            {print " COLD\n";}
}

Perl, from the perspective of conditions, is identical to C, with the only exception that Perl forces us to always use braces, even if the braces contain a single instruction. In that case, the line terminator ; which is optional and we can omit it. In our example code we could have written:

if ($v == $n) {
    print "Well Done!\n"
}

Just like in C, in Perl it is mandatory to use parentheses around the conditions when we use the if-elsif-else form.

DID YOU KNOW…

The characters <> are known as the diamond operator, due to its shape. It is used to read lines from standard input. In reality it is used to read data from any file descriptor, but when we don’t specify any between the signs < and > it simply reads from standard input.

It is possible to omit the braces in if expressions when we only want to execute a single instruction. Unlike C, in this case, the condition goes to the end of the instruction preceded by if, and in that case it is not necessary to use parentheses in the condition, although nothing happens if we put them.

die "Only positive numbers" if $v < 0;

I’M A BEGINNER

The die instruction (Dies in English) ends the program displaying the message we pass as a parameter.

Perl does not offer a switch instruction as part of the language, although there is a package that extends the language with a version of the switch command. However, Perl offers us a ternary operator that works exactly the same as its C equivalent (in fact, they are identical).

In the example program we have used the abs function to calculate our intermediate value, but we could implement the same functionality with the ternary operator:

$h = ($v > $n) ? $v - $n : $n - $v;

As you can see, Perl, like other languages we will see later, offers a special construction for the case where it is necessary to add a new condition to the else block. This construction is called elsif in Perl. You can see how to use it in the example program to generate the hint.

Perl allows you to define three types of variables: scalars, arrays, and hashes. Perl differentiates these variables by prefixing a different symbol to the name of each variable depending on its type. Thus, scalar variables (those that can only contain a single value) are marked with the symbol $. Arrays or matrices with @ and hash tables with #.

I’M A BEGINNER

Perl does not initially differentiate between data types. The value stored in a Perl variable will be used in the most convenient way (number, string, …) according to the context.

While it is possible to print strings using format strings like in C, and it can be useful at times, Perl, like most scripting languages, allows us to print values in a much simpler way. We can construct the string to be printed using the concatenation operator ., which allows us to… well… concatenate strings. The following line shows how we use that operator to construct the message to be printed.

print "Number is " . (($v < $n) ? "HIGHER" : "LOWER") . "\n";

But Perl also allows us to print variables directly by including them within the string, which is known as String/Variable Interpolation and is a functionality present in many other programming languages.

The previous code could have been written like this:

$pista = ($v < $n) ? "HIGHER" : "LOWER";
print "Number is  $pista\n";

As you can see, we simply use the variable within the string to print it. For this to work, the string must be defined with double quotes. Single quotes can also be used to define a string in Perl, but in that case the string will be printed exactly as it is written.

Perl does not allow defining constants natively, although there are various packages that allow us to include this functionality in our programs. The most common are constant and readonly which can be used as follows:

use Readonly;
Readonly $V = 42;

use contant V => 42;

Observe that when we use constant we do not specify the variable type and Perl will substitute the occurrences of that value at compile time (which happens just before executing our script). Therefore, it is not possible to do string interpolation with constant:

use constant V => 42;
print "Value is V";    # Prints "Value is  V"
print "Value is " , V; # Prints "Value is  42"

DID YOU KNOW…?*

There are Perl modules for almost anything, including defining constants, although the two forms we have commented on are the most typical. For example, the Const::Fast package works like constant but allows string interpolation.

In general, the easiest way to work with constants is to assume a certain naming convention. It is common to use uppercase letters for the names of constants. In this way, any variable whose identifier is in uppercase is interpreted as a constant by the programmer and will not try to assign values to it.

Summary

  • Supports if ... [elsif] ...[else] ...
  • Supports reduced form Command if (condition);
  • Supports ternary operator (condition) ? true_value : false_value
  • Does not support booleans: ==0 -> FALSE and !=0 TRUE
  • Does not support switch
  • Does not support constants natively (modules constant and readonly)

Related Posts

GNU/Linux Programmer's Solver - Introduction

Programming exercises in 18 Programming Languages

Read

linuxprogramming

GNU/Linux Programmer's Solver - Hello World in Perl

Hello World program in Perl. Basic structure, comments and string literals

Read

PROGRAMMING PERL HELLO WORLD

GNU/Linux Programmer's Solver
Chapter 2 - Conditionals

Conditionals are the may way to add logic to your programs.

Read

PROGRAMMING HELLO WORLD

Return to Home Page