Variable Declaration in Perl
In Perl, there are only three types of variables: hashes, scalars, and arrays. Declaring variables in Perl is somewhat different from most common programming languages.
First, what is a variable and how is it characterized?
A variable is an “object” that holds useful information within the programming context. A variable is characterized by three things:
-
Name: Good programming practices suggest naming variables as follows:
- The first character must be a letter;
- Numbers can be used in the variable name but never as the first character;
- According to good programming rules, variable names should be lowercase;
- If combining multiple words, the second word should start with an uppercase letter. Example: testVar.
-
Variable Type: In Perl, the variable types are:
- hash (
%
) - array (
@
) - scalar (
$
)
For those coming from other languages, it might seem strange that you don’t have to declare whether a scalar variable is an integer, float, string, etc. Perl automatically detects the type.
- hash (
-
Value: This is the value the variable will hold in the program. The value can be a scalar, array, or hash.
Hash, array, scalar? What are these?
These are the three types of variables in Perl. Let me explain each one.
A scalar variable holds a single element or value. This does not mean it can only hold a number or only a word — it can hold multiple words or multiple numbers as a single scalar value.
my $nome = Rubem ;
my $morada = "Portugal , União Europeia";
my $numero = 123455667;
An array is a “list” variable that holds multiple values. You might wonder what the difference between a scalar and an array is. The difference is simple: an array can have many scalars, but if a scalar is assigned an array, it will only hold the number of elements in that array.
my @array = (foo, bar, zed);
my $val = @array;
# val will store the number of items instead the value of each array value
After explaining the difference between scalars and arrays, here is how you can create arrays:
my @array = (1..10);
my @array = (teste, tx, px);
my @array = qw(teste tx pc);
# using qw, perl will assume that every word is a separated item
Finally, I will talk about hashes, also known as associative arrays. A hash is a “two-dimensional” variable where each item has an associated value. One list contains the keys, and the other contains the corresponding values.
my %hash = ("linha1" => "Teste");
Each key can only have one value. The example above shows how to define a hash, but there is another way to do the same, as follows:
my %hash = ("linha1" , Teste);
Note: For both arrays and hashes, you can access the entire array/hash or a specific position within it. Remember, both arrays and hashes start counting at zero, meaning the first value is at position zero.