In the previous lesson we learnt what variables were and how to use command line arguments in Perl. We also wrote our second Perl script: the Calculator. In this lesson we will learn how to use If statements and loops and how to open files to read and write into them.
What are If statements and loops?
Every Perl script is made of instructions which tell the interpreter what to do. Depending on the purpose of the script you’ll write different instructions. Sometimes, you might want some instructions to be executed only on certain conditions. To do this,you’ll use If statements. A typical If statement is an instruction which defines three elements:
- A condition
- A set of instruction to execute if the condition is met
- A set of instruction to execute if the condition is not met
For instance,consider the following code:
if ($time > 12){
print “Good Afternoon“;
}else {
print“Good Morning“;
}
In this If statement, the condition is ($time > 12). If the condition is met then the script prints “Good afternoon“, otherwise it prints “Good morning“.
Sometimes, you might want some instructions to be executed more than once. For this you can use loops. A typical loop is composed of a condition and a set of instructions to execute. There are different kinds of loops and we will study them in the chapters below.
If statements in Perl
Perl is a very flexible language and this is particularly true when it comes to If statements.
Simple “if” statements
The most common form of If statement in programming is composed of a condition (between parenthesis) followed by a set of instructions which are placed between brackets. For instance:
if ($time > 12) {
print “time is $time\n“;
print“Good Afternoon\n“;
}
Although it is considered bad practice, you don’t have to write the brackets if there is only one instruction in the If statement:
if ($time > 12)
print “Good Afternoon\n“;
To avoid any possible confusion, it is recommended to always write the brackets, or, if there is only one simple instruction to place the condition and the instruction on the same line:
if($time > 12) print “Good Afternoon\n“;
In Perl, you can also write the condition after the instruction itself. For instance:
print “Good Afternoon\n“ if($time > 12);
“else” and “elsif” statements
Similarly, you can define an “else” block of instructions,which will be executed if the condition is not met:
print“time is $time\n“;
if ($time > 12) {
print “GoodAfternoon\n“;
}
else {
print “Good Morning\n“;
}
Sometime you may want to do something depending on more than one condition. Of course you can always define If statement within others, but you can also use elsif,as a contraction of ?else, if (something else..)?:
if ($time < 12) {
print “GoodMorning\n“;
}
elsif ($time < 20) {
print “Good Afternoon\n“;
}
elsif ($time < 23) {
print “Good Evening\n“;
}
else {
print “Good night\n“;
}
“unless” statements
In Perl, you can use the unless statement. It behaves exactly like the If statement but executes the code if the condition is not met. For instance the following code prints Good night if it’s more than 11pm:
print “Good night\n“ unless($time < 11pm);
Loops in Perl
There are many different kinds of loop in Perl. Here are the most common types.
“while” loop
This loop executes a block of code while a condition remains true.For instance, the following code prints Hello three times:
$i = 0;
while ($i < 3) {
print “Hello\n“;
$i = $i + 1;
}
“until” loop
This loop executes a block of code until a condition becomes true.For instance, the following code prints Hello three times:
$i = 1;
until ($i > 3) {
print “Hello\n“;
$i = $i + 1;
}
“for” loop
The for loop is composed of four elements:
- A starting assignment
- A condition
- An incrementation
- A set of instructions
The notation of the For-loop is as follows:
for (starting assignment; condition; incrementation) {
instructions
}
The for loop starts by executing the starting assignment. Then,while the condition is met, it keeps executing the instructions and the incrementation. For instance the following For-loop prints Hello three times:
for ($i = 0; $i < 3; $i = $i + 1) {
print “Hello\n“;
}
Note that the ++ operator is usually used to increment a variable,so we could have written $i++ instead of $i = $i + 1;
In Perl, you can also use the For-loop with a ?range operator?.The notation for the range operator is ?..?. For instance, the following code prints ?Hello? three times:
for (1..3) {
print “Hello\n“;
}
“foreach” loop
The foreach loop is used to iterate through the elements of an array. For instance, the following code prints the days of the week:
@days = (“Monday“, “Tuesday“, “Wednesday“, “Thursday“, “Friday“, “Saturday“, “Sunday“);
foreach $dayOfTheWeek (@days) {
print “$dayOfTheWeek\n“;
}
You can also use the foreach loop to iterate through the keys of an hashtable. For instance, the following code prints the days of the week:
%days = ();
$days{“Monday“} = 1;
$days{“Tuesday“} = 2;
$days{“Wednesday“} = 3;
$days{“Thursday“} = 4;
$days{“Friday“} = 5;
$days{“Saturday“} = 6;
$days{“Sunday“} = 7;
foreach $day (keys
%days) {
print “$day is the day number $days{$day} of the week\n“;
}
File Handling
The Perl language was designed to make file handling easy and efficient, so you’ll probably won’t have any problem opening files and reading them.
Opening and closing files
In order to open a file, you’ll use the ?open? instruction which takes two arguments: the name of a file handle and the name of the file itself. The file handle is like a variable which represents the handling of the file within the script. For instance, in the following code we’re opening the file ?clients.txt? with a filehandle called CLIENTS:
open (CLIENTS, “clients.txt“);
By default, the file is open in read-mode, which means you can only read from it. You can decide to open a file in write-mode, in order to be able to write into it. If the file already existed or had some data written into it, the data will be lost. To open a file in write-mode simply add a “>” in front of the file name:
open (CLIENTS, “>clients.txt“);
If you’d rather keep the data written in the file, you can open the file in append-mode. This way, the data will be kept, and what you’ll write in the file will be appended to it. In order to do this add a “>>” in front of the file name:
open (CLIENTS, “>>clients.txt“);
The “open” instruction returns true if it managed to open the file, false otherwise. You can use this value in order to test the success of the operation. For instance, the following code opens the file in write-mode and prints “Insufficient privileges” if the script doesn’t manage to do so.
open (CLIENTS, “>clients.txt“) or print “Insufficientprivileges\n“;
Remember to always close the files once you’re finished with them.If you don’t your changes might be lost. In order to close a file,simply use the “close” instruction on the filehandle:
close (CLIENTS);
Writing into files
Once the file is open in write mode you can write into it simply by writing into its filehandle. The ?print? instruction writes things on the screen by default, but you can specify a filehandle to write into. For instance, the following code adds a line “Mr John Doe” in the end of the “clients.txt” file:
open (CLIENTS, “>>clients.txt“) or die “Insufficientprivileges\n“;
print CLIENTS “Mr John Doe\n“;
close (CLIENTS);
Reading data from files
There are many ways to read the content of a file. Here are the two most common ways in Perl.
Copying the content of the file into an array
You can copy the whole content of the file into an array. Each line will then correspond to an element of the array. Here is an example:
open(CLIENTS, “clients.txt“);
@lines = <CLIENTS>;
close(CLIENTS);
print @lines;
Looping through the filehandle
Alternatively you can loop through the filehandle in a while loop by writing while($line = ) (think of it as ?while there are lines in the clients file, I’m assigning the current line to $line):
open (CLIENTS, “clients.txt“);
while ($line = <CLIENTS>) {
print $line;
}
close (CLIENTS);
As you can see, Perl makes it very easy to manipulate files. In the next lesson we’ll look at how to search for a particular element within a file, and how to handle and manipulate strings.