Perl Programming/Array variables
Perl syntax includes both lists and arrays.
A list in perl is an ordered set of scalar values. It is represented in your code as a comma-separated sequence of values, which may or may not be contained in scalar variables. Lists can be used to make multiple assignments at once, and can be passed as arguments to several built-in and user-defined functions:
#!/usr/bin/perl use strict; use warnings; my ($length, $width, $depth) = (10, 20, 15); print "The values are: ", $length, $width, $depth;
Parentheses are not required in the construction of a list. They are used only for precedence.
Alternate List ConstructionEdit
When creating a list of several strings that do not include spaces, Perl provides a shortcut to get around typing multiple quotes and commas. Instead of
($name1, $name2, $name3, $name4) = ('Paul', 'Michael', 'Jessica', 'Megan');
you can use the qw// operator. This operator uses any non-alpha-numeric character as a delimiter (typically the / character), and encloses a space-separated sequence of barewords. A delimeter separates the command with the arguments. The above line is identical to the following:
($name1, $name2, $name3, $name4) = qw/Paul Michael Jessica Megan/;
and both are equal to this:
($name1, $name2, $name3, $name4) = qw(Paul Michael Jessica Megan);
The last example uses the open and close parenthesis as a different delimeter. If there is an open and close version of the delimiter you choose, you need to use them both. Otherwise just repeat the same symbol twice. For example, you cannot type qw<Paul Michael< you have to type qw<Paul Michael>.
You can also abuse the glob syntax, when the strings do not include shell metacharacters:
($name1, $name2, $name3, $name4) = <Paul Michael Jessica Megan>;
The resulting strings from the qw// operator are single-quoted, meaning no interpolation happens in the set. If you need to include a variable in your list, you cannot use this method.
As shown above, lists can be used to make several assignments at once. If the number of variables on the left is the same as the number of values on the right, all variables are assigned to their corresponding values, as expected.
If there are fewer variables on the left than values on the right, the 'extra' values are simply ignored:
#!/usr/bin/perl ($length, $width) = (10, $w, 15); #$length gets 10, $width gets the value of $w. 15 is ignored
If there are more variables on the left than values on the right, the 'extra' variables are assigned the default undef value:
#!/usr/bin/perl ($length, $width, $depth) = (10, $w); #$length gets 10, $width gets the value of $w. $depth is undef
The existence of list assignment creates the ability to 'swap' two variables' values without the need of an intermediary temporary variable:
#!/usr/bin/perl $foo = 10; $bar = 5; ($foo, $bar) = ($bar, $foo); #$foo now equals 5, while $bar equals 10;
An array in Perl is a variable that contains a list. An array can be modified, have elements added and removed, emptied, or reassigned to an entirely different list. Just as all scalar variables start with the $ character, all array variables start with the @ character.
It is a common and frequent mistake in Perl to use the terms 'list' and 'array' interchangeably. They do not have the same meaning.
A decent analogy is that a list (such as qw/foo bar baz/) is to an array (such as @values) as a string (such as 'Paul') is to a scalar variable (such as $name).
Arrays are assigned lists of values. The list of values can be arbitrarily large or small (it can even contain 0 elements).
#!/usr/bin/perl @nums = (1,2,3,4,5); @more = 6..1000; #using the 'range' operator @none = (); # empty array. @names = qw/Paul Michael Jessica Megan/; @all = (@nums, @more); #@all contains all integers from 1 to 1000
That last example exemplifes a feature of Perl known as 'array flattening'. When an array is used in a list, it is the array's elements that populate the list, not the array itself. As stated above, a list is a set of scalar values only. Therefore, the @all array contains 1000 elements, not 2.
Although this implies you cannot create an 'array of arrays', or 'two-dimensional arrays', such things do exist in Perl. They are simulated by using references.
Arrays in scalar contextEdit
When an array is used in scalar context - either by assigning a scalar variable to the array's value, or using it in an operation or function that expects a scalar - the array returns its size. That is, it returns the number of elements it currently contains
#!/usr/bin/perl @names = ('Paul','Michael','Jessica','Megan'); $how_many = @names; print "I have a total of $how_many names\n";
A common misconception is that a list in scalar context will also return its size. This is untrue. In fact, there is no such thing as a list in scalar context: using the comma operator in a scalar context does not create a list, instead it evaluates each of its arguments, left to right, and returns the last one:
$name = ('Paul','Michael','Jessica','Megan'); print "The last name in my list is $name\n";
Printing an ArrayEdit
There are two general ways of printing the values of an array. You can either print the list of items in the array directly, or you can interpolate the array in a double-quoted string.
@names = qw/Paul Michael Jessica Megan/; print "My names are: ", @names, ".\n"; print "My names are: @names.\n";
In the first example, the print function is being given a list of 6 arguments: the string 'My names are: ', each of the four values in @names, and the string ".\n". Each argument is printed separated by the value of the $, variable (that defaults to the empty string), resulting in the values from the array being 'squished' together:
My names are: PaulMichaelJessicaMegan.
In the second example, the print function is being given exactly one argument: a string that contains an interpolated array. When Perl interpolates an array, the result is a string consisting of all values in the array separated by the value of the $" variable (that defaults to a single space):
My names are: Paul Michael Jessica Megan.
Both the $, and $" variables can be changed to any string you like. For example, to separate the array's items with a comma and a space instead of just a space:
$" = ', '; print "My names are: @names.\n";
My names are: Paul, Michael, Jessica, Megan.
You generally do not want to do that as this may cause problems in other parts of your program depending on the default values of those variables though! A safer way to print your arrays with custom separator will be explained later.
Accessing Elements of an ArrayEdit
The elements of an array are accessed using a numerical reference within square brackets. Because each item within an array is a scalar value, you need to use $ when referencing a value. The first element of an array is number 0 and all the others count up from there.
A negative number will count down from the right side of the array. This means that -1 references the last element of the array and -3 references the third to last element. Let's see some examples:
@array = (1, 2, 3, 4, 5); print $array; # Prints 1 print $array; # Prints 4 print $array[-1]; # Prints 5
What if you need to know the last index? $#array will return it for you:
@array = (1, 2, 3, 4, 5); print $array; # Prints 5 print $array[-1]; # Same as above print $array[ $#array ]; # Also prints 5
A common mistake is to do this:
print @array; # Also prints 1, but for the wrong reasons
In fact @array is a slice (that is, a sub-array of an array) that contains one element, whereas $array is a scalar that contains the value 1.
Common array functionsEdit
Command line argumentsEdit
As you may wonder, Perl scripts support command line arguments. The entire list of parameters is stored in the array @ARGV, with the first entry containing the first command line argument. If no command line parameters were passed, @ARGV is an empty array.
The array functions and operators listed above can easily be used to detect the passed command line arguments and to detect the number of arguments provided.