Welcome to Linux Forums! With a comprehensive Linux Forum, information on various types of Linux software and many Linux Reviews articles, we have all the knowledge you need a click away, or accessible via our knowledgeable members.
Find the answer to your Linux question:
Site Navigation
Linux Forums
Linux Articles
Product Showcase
Linux Downloads
Linux Hosting
Free Magazines
Job Board
IRC Chat
RSS Feeds
Free Publications

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 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 $timen";
print"Good Afternoonn";

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 Afternoonn";

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 Afternoonn";

In Perl, you can also write the condition after the instructionitself. For instance:

print "Good Afternoonn" 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 $timen";
if ($time > 12) {
print "GoodAfternoonn";
else {
print "Good Morningn";

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 "GoodMorningn";
elsif ($time < 20) {
print "Good Afternoonn";
elsif ($time < 23) {
print "Good Eveningn";
else {
print "Good nightn";


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 nightn" 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 "Hellon";
$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 "Hellon";
$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 "Hellon";

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 "Hellon";

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 "$dayOfTheWeekn";

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 weekn";

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 "Insufficientprivilegesn";

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 "Insufficientprivilegesn";
print CLIENTS "Mr John Doen";
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.

Lesson 2

Lesson 4

Rate This Article: poor excellent
Comments about this article
Thank you.
writen by: An appreciative reader on 2006-07-06 23:30:59
This was more than helpful in help me migrate from PHP to perl, as much of the syntax of PHP is taken from perl apparently, pretty cool, easy instructions and wonderful fluentcy as far as reading this tutorial. Thank you LinuxForums for facilitating the face, and Thank you Clement for the great help.
RE: Thank you. written by An appreciative reader:
writen by: danoco on 2006-07-21 15:15:34
Looking forward to the next lession.
RE: More! written by danoco:
Straight to the point
writen by: Joe on 2006-07-29 23:23:50
Straight to the point, no faff, really easy on the mind. Look forward to the next, great job!
RE: Straight to the point written by Joe:
formatting errors
writen by: mike on 2007-01-08 15:25:54
RE: formatting errors written by mike:
writen by: mike on 2007-01-08 15:27:13
open(CLIENTS, "clients.txt"); @lines = ; close(CLIENTS); print @lines; This should be: open(CLIENTS, "clients.txt"); @lines = <CLIENTS>; close(CLIENTS); print @lines;
RE: ugh written by mike:
was able to write to the text file but..
writen by: steve on 2007-08-29 14:34:07
I was able to write to the text file but when I tried to use this bit f code ... print "Content-type:text/htmlnn"; open(CLIENTS, "clients.txt"); @lines = ; close(CLIENTS); print @lines; I kept getting an internal server error message. I also tried the while loop to display the lines of the text file and that code also gave me the same error messages. Does anyone know what Im doing wrong? Well this is still the best perl tutorial I have been able to find.
RE: was able to write to the text file but.. written by steve:
try this
writen by: saurabh baid on 2008-03-14 01:37:25
RE: try this written by saurabh baid:
writen by: on 2009-05-11 12:08:22
#!/usr/local/bin/perl open (CLIENTS, 'data.txt'); while (<CLIENTS>) { chomp; print "$_n"; } close (CLIENT); [/quote]
RE: Filehandling written by :
writen by: on 2009-05-11 12:09:07
Have you tried to include the whole path of the file location. i.e, is you file within the same directory as the perl script itself? Also, include the function die, that is open (CLIENTS, 'data.txt') or die "whats the error $!" to see what is happening on the backend.
RE: Filehandling written by :
Looping through the filehandle
writen by: mehdar on 2010-01-04 14:05:47
the line :
while ($line = ) {
should be :
while ($line = < CLIENTS > ) {

CLIENTS is the filehandler which will be used to identify the file we are looping through ,

Thank you
RE: Looping through the filehandle written by mehdar:

Comment title: * please do not put your response text here