Perl Variables

By: Nico Coetzee
Date: 7 June 2003
Revision: 1

This short piece should serve as a crash course intro to Perl variables. Various other Perl functions are also used, and I will try to explain as good as I can as I go along. Discussions about this page can be made on our mailing list. From time to time, I may add to this page, especially the archived discussions - so newbies should visit once in a while :)

When discussing this topic on our mailing list, please start the subject line with [art001], or just click here


A short discussion about the various Perl variables

If you don't know what variables[ 1 ] are I can only assume that you are a complete beginner at programming. But, to be safe, I will first give a loose definition of what a variable is:

A variable is a named ( defined ) container that holds a value or values.

Note : This is not an article intended for _complete_ newbies to programming - some experience and knowledge of basic concepts, like variables, commenting and so forth are recommended. This guide only explains variables in a little more detail.

Existing Programmers new to Perl sometimes find it a bit confusing as we don't define Perl's variables based on the type of information it stores. In many other languages like Pascal, C/C++ and others, you have to define a variable by the type, for example the Integer type ( a variable that holds only whole numbers ). In Perl any variable can hold any type of information. We define a variable based on HOW we want to store the information. In this article we will look at:

$myvar = "My Value";
$v1 = $v2 = 0;
$a = 5;
$b = "3";
$c = $a * $b; # $c = 15
As you can see, the variable name starts with the '$' sign, and the value is assigned to the right. You can assign one value to multiple variables in one row, as indicated. Strings should be entered between quotes, but this is optional for numeric values.
@mylist = ( "1", "2", "3" );
$firstitem = $mylist[0];

@colours = ( "White", "Black", "Red" );

An array holds a list of separate pieces of information with a shared relationship. Arrays are defined with a '@' sign in front of the variable name. A typical example may be a list of colours. The first item always has an index position of 0, the second item 1 etc., so when you are referring to a particular item in the list, you have to use the index number between square brackets, with a '$' sign in front of the variable.

As you can see from the example, it's possible to assign one of the list values to a scalar variable ( $firstitem ).

(Associative Arrays)
%emails = ();	# declare an empty hash
%emails = (
  "Mike"  =>  "",
  "John"  =>  ""

$mike_email = $emails{ "Mike" };

$myref = "John";
$john_email = $emails{ $myref };

Hashes start with the '%' sign, but when we are referencing a hash, we use the '$' sign and the index is in curly brackets directly after the variable name. The index can be either a hard coded value, or a scalar variable.

Hashes are good for storing information that can be indexed by a unique value ( index ).

With the intro done, it's time we do some practical work.

top | contents | section start

Our first script - a look at all three variables in one go

Warning : - I assume you already know how to execute a Perl script.

Note : - The script(s) has been tested on Linux, Kernel 2.4.x with Perl 5.8.0 - in other words, I don't know how well it runs under Windows and other popular Operating Systems.

You can find the original script here, or, if you prefer - I have also made a colour coded HTML page of the script. I have a line by line discussion below:

Line #

The "shabang" line - used by Unix Operating Systems to identify the interpreter. As a rule, this line always start with #! followed by the path to the Perl executable. To locate Perl on your Unix system, type the following from a terminal/console:

	$ which perl

You should use the returned line after the #! characters.

A simple scalar definition. Here we assign the value 'Peter Pan' to a scalar named $myname

To print the value of a variable, we can use the normal print statement.

This is a simple stopwatch where we assign a start time to a scalar ( Unix time stamp - integer, in seconds ), then sleep for three seconds, and take another time reading. We then calculate the time difference ( in seconds, since time1 and time2 are both in seconds ), and assign the result to the final scalar which is printed.

This is a sample of using Perl's built in variables ( variables that are defined on Script Execution ). The array @ARGV holds each command line argument, and if you execute your script like this:

$ ./ hello world

the @ARGV array now holds two values:

  • $ARGV[0] holds the first argument - 'hello'
  • $ARGV[1] holds the second argument - 'world'

Here we declare an empty array.

Yet another scalar definition.

Here we start a for loop ( similar to the C/C++ style ) which will loop 4 times. The line literally reads: "for variable $t starting at 1 ( $t = 1; ) and stopping at 4 ( $t < 5; ) incrementing with 1 after each loop ( $t++ ), DO ( { )".

On line 46 we combine the constant in $myconstant with the current value of the loop counter ( $t ) to form a new value, which is stored in a scalar variable $mytempvar.

Line 47 takes the $mytempvar, and adds it ( push ) to the array @myarray.

Line 49 indicates the end of the loop.

This is where we print ALL values of an array. We accomplish this with a foreach loop. Note that in line 51 we don't send a newline character ( \n ) to standard output, so the variables will be printed out on the same line. The $_ variable is also a special built in variable that holds the current value of the foreach loop.

foreach works like this: It will go through each value in a list, one at a time, which you can then manipulate. Another - longer way - of accomplishing the same result would be:

	51 print "Items: ";
	52 # assign the number of items in the list to $linecount
	53 $linecount = @myarray;
	55 for ( $t = 0; $t < $linecount; $t++ ) {
	57 		print "\'$myarray[$t]\' ";
	59 }
	60 print "\n\n";

The output should remain exactly the same.

We now start to play with hashes. Line 63 is similar in nature to line 41 ( see above ). As you can see, the logic is simple - we assign the value Apples to index Item 1 and so on. When we want to know what he value of Item 1 is, we simply refer to $myhash{ "Item 1" }, which will of course contain the same value as we assigned in the beginning.

Note : - line 64 to 69 could have been placed on one line, but it makes it easier to read if we space it over several lines and with some fancy use of TABS.

We can also assign the index to a scalar variable, and use that as a reference to an index. The logic should be straight forward - I hope :)

Like we did with the array, we can also loop through a hash and print all the values stored in it. The big difference is that we can no longer use a loop with an integer, as we use defined index values, which may not make any logical sense. To get around this, we can extract the index values of the hash, and place in in a scalar - one at a time, hence the line: 'foreach $myindex ( keys %myhash ) {' should be read like this: "Extract the keys ( keys %myhash ) from the hash, and assign it to $myindex, looping through one index at a time ( foreach $myindex )".

top | contents | section start


[ 1 ] -

top | contents | section start

Copyright © 2003. All rights reserved. Nico Coetzee. Please be so kind as to ask permission before publishing this page else where. You are encouraged to rather hyperlink to it. All sourcecode mentioned on this page is licensed under the GPL.