Jump to content

Recommended Posts

Posted

Lesson 2

 

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:

 

./myScript.pl

 

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: $nbArguments\n";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 = $result\n";

 

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.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...