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 Perl was and how to use the interpreter to run Perl scripts. We also wrote our first Perl script: HelloWorld.pl. In this lesson we will learn how to use variables and command line arguments. We will then use them in order to write our second Perl script: a calculator!

Learning Perl - Lesson 1

What are variables?

Variables are used in every computer language. If you are new to programming, remember the variables used in algebra equations. For instance, consider the following equation:

a + 5 = 7

In this equation, there is only one variable. Its name is "a" and its value is "2". Variables always have a name and they always have a value. In algebra their value is usually a number. In programming, their value can be a number, a character, a string (which means a sequence of characters), or even a complex object such as an array, a hashtable, a data structure, etc... Throughout the lessons we will use variables to store many different types of objects or values and you will become more familiar with the different data types that a variable can represent.

Variables in Perl

In Perl, there a three types of variables: * scalar variables, * arrays, * hashtables.

Scalar variables store a single value. In Perl, scalar variables names are always prefixed with a dollar sign. For instance:

$a = 2;
$message = "Hello World!";

Arrays can store many values. In Perl, arrays are always prefixed with an at-sign. For instance:

@colors = ("red", "green", "blue");@primaryNumbers = (1, 2, 3, 5, 7);

Hashtables are a special kind of array: associative arrays. They are like arrays, but for each of the value they store, they also store a corresponding name or label. They consist of pairs of elements - a key and a data value. In Perl, hashtables are always prefixed with a percent sign. For instance:

%phoneNumbers = (Alicia =>  "090-64-773315",             Tom => "085-153-3214",             Jimmy => "085-285-4545");

In this lesson we will focus on scalar variables and arrays. They are simple to use and they will help us write our calculator.

What are command line arguments?

In the previous lesson we first called our script by invoking the Perl interpreter:

perl myScript.pl

Then we saw how to make an implicit call to the interpreter so that the script could be called directly:


Whether we call the interpreter implicitly or explicitly, we can give arguments to the script. These arguments are given while calling the script, and simply put after the script name:

./myScript.pl argument1 argument2 argument3

For instance, instead of having a script which writes "Hello World!" on the screen, and thus doesn't need any argument, we will write a calculator in this lesson. Our calculator will calculate the result of a simple equation which we will give as a command line argument. For instance, if we wanted our calculator to add 5 and 6, we would call it like this:

./calculator.pl 5 + 6

In this example, we gave three command line arguments:

  • 5
  • +
  • 6

The Perl script will have to look at these arguments, identify the second argument to know what operation to do with the first and third arguments, calculate and print the result on the screen. Command line arguments in PerlWhen the interpreter runs the Perl script it stores the command line arguments in an array called @ARGV. Note that the Perl language is case-sensitive, so it is important to use capital letters here. @ARGV is an array, and like every array in Perl you can do the following on it:

  • Get the first element of the array by typing $ARGV[0] (note that as this is a single value it is represented by a scalar variable and prefixed with a dollar sign).
  • Get the second elements of the array by typing $ARGV[1]... etc.
  • Get the index of the last element in the array by typing $#ARGV.

Note that arrays always start from 0, not from 1. Therefore the first element of an array, is element 0, not element 1. For instance element number 12 corresponds to the 13th element of an array. This is a convention in many programming languages. The index of the last element in the array corresponds to the number of elements - 1.

In our example, we call our calculator by giving it three arguments:

./calculator.pl 5 + 6

Therefore we can expect the @ARGV array to contain three elements, $#ARGV being equal to 2 and $ARGV[0], $ARGV[1] and $ARGV[2] respectively being equal to 5, "+" and 6.

Your second Perl script, the Calculator!

You nearly know everything you need in order to code your second Perl script and to write a nice calculator. In fact you could do it yourself now! As we said before, there are more than one way to do something in Perl. Try to program the calculator by yourself, and then have a look at the solution below.

Create a file called calculator.pl and write the following into it:

#!/usr/bin/perl$nbArguments = $#ARGV + 1;print "number of arguments: $nbArgumentsn";exit(1) unless $nbArguments == 3;$a = $ARGV[0];$b = $ARGV[2];$operation = $ARGV[1];if ($operation eq "+") {        $result = $a + $b;}elsif ($operation eq "-") {        $result = $a - $b;}elsif ($operation eq "/") {        $result = $a / $b;}elsif ($operation eq "x") {        $result = $a * $b;}print "$a $operation $b = $resultn";

Make the script executable:

chmod a+rx calculator.pl

Run the script :

./calculator.pl 5 + 6./calculator.pl 11 - 2./calculator.pl 4 x 3./calculator.pl 33 / 3

The script works as expected, but there probably are a lot of instructions you didn't fully understand within this script. So let's look at them.

The first line tells where to find the interpreter, so that we can call the script directly.

The second line takes the index of the last element from the @ARGV array and adds 1 to it. That way it gets the number of command line arguments given to the script and stores it in a variable called $nbArguments.

The third instruction simply prints the number of arguments on the screen.

There is a lot to say about the fourth instruction (exit(1) unless $nbArguments == 3;):

  • "exit" is a Perl function which makes the script stop and return a given code to the shell. In this example the script stops and returns 1 to the shell. 1 is a Unix convention which means that there was an error.
  • "unless" is the opposite of "if". These are Perl statements. In this example, "exit" is called unless the following statement is true "$nbArguments == 3".
  • In Perl, and in many programming languages, the equal sign is used to affect values to variables. For instance, when we wrote $nbArguments = $#ARGV + 1, we assigned a value to $nbArguments. The double equal sign "==" is a comparison operator which returns true or false depending on the fact that the variables or values on both side are equal or not. Perl also provides another operator "eq" which compares strings. Try to use "eq" for string comparisons and "==" for numbers. Remember that the "=" sign assigns values and is not a comparison operator.
  • In brief, (exit(1) unless $nbArguments == 3;) means that the script will stop unless three command line arguments were given.

The three next instructions simply assign the three command line arguments to variables. We stored the first one in $a, the third one in $b and the second on in $operation.

Then, depending on the value of $operation, we made a different calculation with $a and $b and stored the result in a variable called $result. Note that we used "if" and "elsif" statements. We will come back to these statements later, but for the moment remember that "elsif" is a contraction for "else if...". Also, note that we used brackets to clearly identify blocks of code between the if statements and that we indented our code. In general, unless you have a very simple one liner to write, use brackets for each if statement and always indent your scripts.

The last instruction writes a summary of the operation and its operands as well as the result on the screen.

In this lesson we learnt how to use variables and command line arguments. We also had a quick look at If statements, comparisons operator and a few operations. In the next lesson, we'll manipulate text files and go a bit further in using operators and other statements.

Lesson 1

Lesson 3

Rate This Article: poor excellent
Comments about this article
Please - lesson 3
writen by: decepticon on 2006-06-14 16:07:34
This is a great tutorial and I am already a little more confortable with perl. Please coninue these lessons!
RE: Please - lesson 3 written by decepticon:
writen by: Andy on 2006-06-22 09:52:36
Thank you for an excellent lesson in perl. I have never had such a good tutorial. Please Please Please keep these coming. I feel like a programmer already :-)
RE: Excellent! written by Andy:
keep going please
writen by: brokndodge on 2006-06-28 11:16:29
I got so excited about the first lesson that i jumped right into an existing script that didn't do what i want it to. It's been a battle learning perl and understanding what the script does and where it does it. this lesson helps some. can't wait for lesson 3.
RE: keep going please written by brokndodge:
writen by: Frank on 2006-06-28 14:29:46
Just refreshing my memory. Very straight to the point
RE: perl written by Frank:
Great Job
writen by: Chev on 2006-07-25 13:46:25
I took an OS Scripting class last year (I'm a student) and I have to take Perl next year. This is not only helping me review scripting, but giving me a start on Perl. Can't wait for the next Lesson!
RE: Great Job written by Chev:
writen by: Roy on 2006-11-20 11:43:25
Kinda worked.... only printed the number of arguments :~> ./calculatorweb.pl 7 * 8 number of arguments: 33 ... did not print the results
RE: ? written by Roy:
writen by: Roy on 2006-11-20 11:48:55
Sorry.. I am a retard.. Works great... I just need to read more and look a pictures less.. lol...
RE: :) written by Roy:
The trick to learning PERL
writen by: Festus Wall on 2007-01-06 01:20:42
1. Let your cat walk on the keyboard. 2. Debug. (For the noobs... not my joke but I love it)
RE: The trick to learning PERL written by Festus Wall:
* is a special char in Perl
writen by: pat on 2008-02-06 15:34:55
RE: * is a special char in Perl written by pat:
writen by: Bloom Star7 on 2008-03-19 02:08:53
RE: written by Bloom Star7:
Use strict
writen by: Anonymous on 2008-04-13 19:18:47
Can you write a tutorial that teaches me to use strict? because the scripts you are feeding me DO NOT WORK with use strict.
RE: Use strict written by Anonymous:
Good tutorial, but No newlines?
writen by: Jeeves on 2008-05-20 13:47:18
This is a pretty good tutorial with Perl scripting, but my only problem is the fact that it has *no* new lines in it. I mean, I had to put this into a text editor and put the word wrap on it to read. :- Other than that, good job.
RE: Good tutorial, but No newlines? written by Jeeves:
writen by: Noob on 2008-12-29 06:40:15
These tutorials are really excellent, but I'm reading them using Opera and only half the page width is visible. I have to scroll along to read every line and can't see me doing that for 10 lessons! But interesting so far thanks!!
RE: written by Noob:
writen by: atmkp0 on 2009-10-30 01:56:48
so just copy paste the stuff into a notepad or word file. how difficult is that? :P

(sorry. had to reply)
RE: ^^^ written by atmkp0:
print $result or $resultn ?
writen by: stuckl on 2011-07-31 21:43:00
Is the n on $resultn supposed to be there in the print instruction, or is that a typo?

Thanks very much for putting up this tutorial. Much appreciated.

RE: print $result or $resultn ? written by stuckl:
Point d'appui
writen by: hpfeil on 2011-12-08 08:30:27
Just a couple of points, not criticism, just trying to help.
"In the previous lesson we learnt what Perl..." I think you might have meant to say "learned" instead of learnt.

Your introduction of hash variables could be a bit less daunting. A hash is simply an array with arbitrary strings, not numbers, for indexes.

Thank you for introducing Perl so masterfully!
RE: Point d'appui written by hpfeil:
small n00b doubt
writen by: bharadwaj on 2012-05-25 06:40:40
Why does it say:

number of arguments = 20 when I enter something like ./calculator.pl 5 * 6 ??

It however gives proper result when I enter ./calculator.pl "5" "*" "6"

What is the reason and how does that ARGV work??
RE: small n00b doubt written by bharadwaj:

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