Sunday, December 19, 2010

Learn Perl in 10 lessons Lesson 3

What are If statements and loops?

Every Perl script is made of instructions which tell theinterpreter what to do. Depending on the purpose of the script you'llwrite different instructions. Sometimes, you might want someinstructions to be executed only on certain conditions. To do this,you'll use If statements. A typical If statement is aninstruction 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 Ifstatement, the condition is ($time > 12). If the condition is metthen the script prints "Good afternoon", otherwise itprints "Good morning".

Sometimes, you might wantsome instructions to be executed more than once. For this you can useloops. A typical loop is composed of a condition and a set ofinstructions to execute. There are different kinds of loops and wewill study them in the chapters below.
If statements in Perl

Perl is a very flexible language and this is particularly truewhen it comes to If statements.
Simple If-statements

The most common form of If statement in programming is composed ofa condition (between parenthesis) followed by a set of instructionswhich 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 towrite the brackets if there is only one instruction in the Ifstatement:

if ($time > 12)
print "Good Afternoon\n";

To avoid any possible confusion, it is recommended to always writethe brackets, or, if there is only one simple instruction to placethe 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 instructionitself. 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 dosomething depending on more than one condition. Of course you canalways 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";

In Perl, you can use the Unlessstatement. It behaves exactly like the If statement but executes thecode if the condition is not met. For instance the following codeprints �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 mostcommon 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) {

The for loop starts by executing the starting assignment. Then,while the condition is met, it keeps executing the instructions andthe 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, thefollowing code prints �Hello� three times:

for (1..3) {
print "Hello\n";
Foreach loop

The foreach loop is used to iterate through the elements of anarray. 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 anhashtable. For instance, the following code prints the days of theweek:

%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 andefficient, so you'll probably won't have any problem opening filesand reading them.
Opening and closing files

In order to open a file, you'll use the �open� instructionwhich takes two arguments: the name of a filehandle and the name ofthe file itself. The filehandle is like a variable which representsthe handling of the file within the script. For instance, in thefollowing code we're opening the file �clients.txt� with afilehandle called CLIENTS:

open (CLIENTS, "clients.txt");

By default, the file is open in read-mode, which means you canonly read from it. You can decide to open a file in write-mode, inorder to be able to write into it. If the file already existed or hadsome data written into it, the data will be lost. To open a file inwrite-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 openthe file in append-mode. This way, the data will be kept, and whatyou'll write in the file will be appended to it. In order to do thisadd a �>>� in front of the file name:

open (CLIENTS, ">>clients.txt");

The �open� instruction returns true if it managed to open thefile, false otherwise. You can use this value in order to test thesuccess of the operation. For instance, the following code opens thefile in write-mode and prints �Insufficient privileges� if thescript 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 simplyby writing into its filehandle. The �print� instruction writesthings on the screen by default, but you can specify a filehandle towrite into. For instance, the following code adds a line �Mr JohnDoe� 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 thetwo 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. Eachline will then correspond to an element of the array. Here is anexample:

open(CLIENTS, "clients.txt");
@lines = ;
print @lines;

Looping through the filehandle

Alternatively you can loop through the filehandle in a while loopby writing while($line = ) (think of it as �whilethere are lines in the clients file, I'm assigning the current lineto $line):

open (CLIENTS, "clients.txt");
while ($line = ) {
print $line;
close (CLIENTS);

As you can see, Perl makes it very easy to manipulate files. Inthe next lesson we'll look at how to search for a particular elementwithin a file, and how to handle and manipulate strings.

No comments:

Post a Comment