Lists and Array Variables

Perl also enables you to define an ordered collection of values, known as lists, this collection of values can be stored in variables known as array variables.

The array variable name can be any length but it has the following rules

Introducing Lists

A list is a sequence of scalar values enclosed in parentheses

Example Lists

(1, 5.3, "hello", 2)

(1, 5.3, $var)                 # once the element has been assigned the value of $var it remains this
                               # value even if you change $var

( 1, $var1 + $var2)            # 2nd element becomes the value of $var1 + $var2

(1, "This is string", 3)       # you can even use strings as values

Perl enables you to store lists in special variables designed for this purpose, these variables are called array variables.

Example Array Variables

@array = (1, 2, 3, 4, 5);      # here the array variable array contains the list 1, 2, 3, 4, and 5

Note: when the perl interpreter sees a @(at) sign it knows that it is an array.          

The arrays storage units are called elements and you can refer to any element within the array as if it was a scalar value, however when you access a single element the array name must start with a dollar ($) as you are accessing a single scalar value. Elements begin at zero, so when you access the first element it would be $array[0].

Array elements

$scalar = $array[0];           # The first element in the array
$scalar = $array[5];           # The 6th element in the array (remember its starts at zero)

$scalar = $array[$index];      # you can use the value of a variable to access the elements

Here is a complete array example

Simple array Example

@food = qw(apple banana orange lemon melon peach plum);   # array food will contain 7 elements (0-6)

$count = 1;
while ($count <= 7)
   print ("element $count is $food[$count-1]\n");         # using value of a variable to get element

Using List Ranges

Suppose you want to define a list of numbers from 1 to 10, you can use the list-range operator two consecutive periods (..) which makes it simpler.

List-Range Example

@array = qw(1 2 3 4 5 6 7 8 9 10);       # The old way   

@array = qw(1 .. 10);                    # the simpler way
@array = qw(2, 5 .. 7, 8);               # array contains 2, 5, 6, 7 and 8

@array = qw(3..3);                       # will contain one element 3

@array = qw($var1+10 .. $var2+100);      # can use complex expressions to create list ranges

@days_of_month("01".."31");              # list contains days of the month (including leading zeros)

@array = qw( 1 @list 3);                 # you can even use other arrays to populate arrays

Assignment and Array Variables

You can copy one array to another

Copy an Array

@food = qw(apple banana orange lemon melon peach plum);

@food_allergies = @food;

while ($count <= 15)
   print ("I would be very sick if i ate the following food $food_allergies[$count-1]\n");

Substituting array variables in Strings @num = (1, 2, 3);
print(@num, "\n");      # no spaces between numbers when printed: 123
print("@num\n");        # puts a space between array elements: 1 2 3
Assigning scalar variables from arrays

@burgers = ("Big Mac's", "Whopper's");

($mcdonalds, $burger_king) = @burgers;         # assign the array elements to the scalar variables

print("Mcdonalds have $mcdonalds\n");
print("Burger King have $burger_king\n");

($dummy1, $dummy2, $dummy3) = @burgers;        # $dummy3 will have null assigned as not enough elements

Get the length of an array

@food = qw(apple banana orange lemon melon peach plum);

$number_of_food_elements = @food;              # get the number of elements in array food
print ("There are $number_of_food_elements elements in array food\n");

$count = 1;
## Use the scalar variable for the element value
while ($count <= $number_of_food_elements)     # use the number of elements in the while loop (could use
{                                              # @food as well)
   print ("$food[$count-1]\n");

## Use the array itself to get the number of elements
while ($count <= @food)                        # same effect as above
   print ("$food[$count-1]\n");

Array Slices @food = qw(apple banana orange lemon melon peach plum);

@part_of_food = @food[2,3,4];                  # array will have values orange, lemon and melon

@part_of_food = @food[2 ..4];                  # same as above using range-list

$maximum = @food;                              # obtain number of elements in food array
@part_of_food = @food[2 .. $maximum];          # same as above using range-list and scalar variables
Array Slices assigning @food = qw(apple banana orange lemon melon peach plum);

@food[@food .. @food+3] = qw(pineapple strawberry blackberry raspberry); #add to array food

$count = 1;
while ($count <= @food)
   print ("$food[$count-1]\n");

Overlapping slices @food = qw(apple banana orange lemon melon peach plum);

@food[1,2,3] = @food[4,5,6];    # we overwrite existing elements using same array food

$count = 1;
while ($count <= @food)
  print ("$food[$count-1]\n");

Reading an Array from standard input file @input_file = <STDIN>;

$count = 1;
while ($count <= @input_file)
   print ("$input_file[$count-1]\n");

Array Library Functions

Perl provides a number of library functions that work on lists and array variables. You can use them to do the following

Sort an array

@array = ("this", "is", "a", "test");

@array2 = sort (@array);                # array2 will contain ("a", "is", "test", "this");

@num = (70, 100, 8);
@num2 = sort (@num);                    # num2 will contain ( 100, 70, 8 ) not (8, 70, 100) - see below

Note: sort treats numbers as strings

Reverse the elements

@array = ("backwards", "is", "array", "this");

@array2 = reverse @array;               # array2 will contain ("this", "array", "is", "backwards");

Remove the last character from all elements @list = ("rabbit", "12345", "quartz");
chop (@list);                           # list will now contain ("rabbi", "1234", "quart");
Merge Elements

@list = ("here, "is", "a");

$string = join (" ", @list, "String");  # $string will contain " here is a String", whitespace is the join character                    
$string = join ("::", @list, "String"); # $string will contain "::here::is::a::String" :: is the join character

Note: the first argument to join is the join character   

Split a string into array elements $string = "Hello:what:a:nice:day";

@array = split(/:/, $string);           # array will contain ("Hello", "what", "a", "nice", "day");