Perl variables

In any programming language we need to store information, an to retrieve it when needed. Perl has three types of variables:

  • scalar – they can store numbers or text (strings).
  • array – they are ordered lists of scalar.
  • hashes – they are unordered lists of values with a “label” called name.

Scalar are identified by the ‘$’ character. You can assign a value to a scalar with the ‘=’:

$age = 15;
$name = 'Larry';
$age = $age+1;        # an more compact alternative is $age++, if you have to add 1
$combine1 = "$name is $age";
$combine2 = '$name is $age';
print "Double quotes:  $combine1\n";
print "Sinngle quotes: $combine2\n;"

This small script has two assignation, a number and a string. Then we increment the $age variable by 1.
Note that for numbers we don’t use any quote, while for string we use single quotes or double quotes. The difference – as mentioned – is that double quotes are interpreted and substitute $name with the content of the variable itself.

Arrays are list of strings. To create a new array the syntax is a list of comma separated scalars enclosed by round brackets:

@array = ('first', 'second', 15, 16);

each element of the array has an index starting from 0, thus the last element of the array in the example has index 3. As each element of the array is a scalar, we refer to it with the “$” sign, specifying the index:

$firstElement = $array[0];

A special variable is created by Perl and contains the index of the last element:

$lastindex = $#array;


$lastElement = $array[$#array];

Finally hashes are unordered lists of couples of scalar: one is the key and has an associated value.  We’ll see hashes in detail in lesson2.

(in Italian) c’è un buon tutorial su array ed hash in questo sito, valido anche per altri argomenti ovviamente… vi consiglio il corso completo come lettura serale ;).

Tagged , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *