Broad Network


Perl Array

Perl Basics – Part 9

Perl Course

Foreword: In Perl an array is a variable to which a list of values is assigned to. Each value (item) is a literal or a variable representing a literal. In this article I explain the Perl Array.

By: Chrysanthus Date Published: 29 Mar 2015

Introduction

This is part 9 of my series, Perl Basics. In Perl an array is a variable to which a list of values is assigned to. Each value (item) is a literal or a variable representing a literal. In this article I explain the Perl Array. You should have read the previous parts of the series before reaching here, as this is a continuation.

List Examples
Imagine that you are a proprietor of a small company, and you have 10 employees. In your Perl program, you can have their first names in an array, where each list item is a first name. Let the list be: John, Mary, Peter, Augustine, Angela, Susan, Martin, Grace, Paul, Simon.

Another example of list occurs when you are dealing with code names. In a table of business data, code names called IDs often identify the rows in a table. You have code names in other situations in life. In a list of code names, some code names may be letters, others may be a mixture of letters and numbers and yet others may just be numbers. An example of such a list is: HBWE, FGTR, HTNK, 4587, 4526, 4053, AB12, GB58, TG45, RE69.

As another example of array items, you can have a list that is just made up of numbers. An example is: 10, 20, 30, 40, 50, 60, 70, 80, 90, 100. The aim in this tutorial is just to know how to make a list into an array and then manipulate the array.

A list does not need to have only 10 items. A list can have, 0, 1, 2, 3 or more items. I will use any of the above lists to explain the meaning of array and how to manipulate an array.

Creating an Array
You create an array by putting the list items in brackets and then assigning the brackets to a variable. Be careful! A variable to which a list is assigned is different from a variable to which a simple literal (value) such as "letters" or 23 is assigned to. If you are assigning "letters" or 23 to a variable, that variable begins with $. When you are assigning a list to a variable and so forming an array, that variable begins with @ and not $. The second list above is made into an array as follows:

my @arr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

Note the following in the above array: Each letter-only item is in quotes; each number-only item is not in quotes. Each item consisting of letters and numbers is in quotes. That is what you have to be doing in your own programming.

In the above statement, my, is the usual reserved word you have to use when you are typing the variable for the first time. @ shows that you are dealing with an array name; arr is the name of the array. @arr is the array variable.

Sometimes, in programming, you might have to create an array before you know what items will form its list. In that case, the list can be empty when creating the array as in the following statement:

my @arr = ();

When the list is empty, you usually do not have to type empty brackets without items as just done; you would just type this:

my @arr;

This is the preferable way of declaring an empty array.

Populating an Array
An empty array created is said to have no population because it has no items. You can populate (add items) to an empty array. First, know that the syntax to change the content of an array cell (element) or give it a new value is:

      $arrayName[i] = value;

A string is text in quotes. If the value is a string, it is in quotes (single or double). If the value is a number, it does not have to be in quotes. If the value is a mixture of letters and numbers, it should be in quotes (single or double). In the syntax, the array name is begun with $ and not @, since we want to refer to an element in the array and not the whole array itself. The array name is followed by square brackets. Inside the square brackets you have a number. This number is the position of the value (item) in the array. This position number is called the index. Index counting in computing, begins from zero, not 1. So the first element (item) in an array is at index 0, the second at index, 1, the third at index 2, and so on. The following code will create an empty array and populate it:

use strict;

my @rrr;

$rrr[0] = "HBWE";
$rrr[1] = "FGTR";
$rrr[2] = "HTNK";
$rrr[3] = 4587;
$rrr[4] = 4526;
$rrr[5] = 4053;
$rrr[6] = "AB12";
$rrr[7] = "GB58";
$rrr[8] = "TG45";
$rrr[9] = "RE69";

There are 10 elements in the array, with indices from zero to 9 as required. Note that to identify each array element, we use the array name and begin with $ and not @.

Accessing an Element in an Array
Accessing an element means to get at the value of the element of the array. The syntax is:

    $arrayName[i]

You can access an element to read the value or change the value.

Reading the value of an Array Element
The above expression returns the value of an element. The following code reads and displays the value of array element number 5, which has the index, 4:

use strict;

my @rrr;

$rrr[0] = "HBWE";
$rrr[1] = "FGTR";
$rrr[2] = "HTNK";
$rrr[3] = 4587;
$rrr[4] = 4526;
$rrr[5] = 4053;
$rrr[6] = "AB12";
$rrr[7] = "GB58";
$rrr[8] = "TG45";
$rrr[9] = "RE69";

my $var =  $rrr[4];
print $var;

The first statement is “use strict;”. It is recommended to always use strict. The statement after declares the array. It begins as an empty array. The next 10 statements populates the array. The last-but-one statement is:

    my $var =  $rrr[4];

Here, a new variable ($var), which will hold a simple single value is declared. At the same time, the fifth elements value is read and assigned to the variable. Fifth element means index 4. The last statement sends the value of the variable, $var to the browser. The value of the variable, $var is the value of $rrr[4].

Try the above code. Remember, to try a code sample, you should copy and past it in a text editor. Save the file with a name of your choice in the cgi-bin directory. Execute the file at the browser by typing the URL of the file at the address bar of your browser and then click Go. If you tried the above code, you should see the number 4526 at the browser.

Changing the value of an Array Element
The following code uses the same array above, but in list format. The value of the third element (index 2) is changed to “yes”:

use strict;

my @arr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

$arr[2] = "yes";
print $arr[2];

The first two statements are as usual. The third statement creates and populates the array automatically in list format. The last-but-one statement changes the value of the third element from "HTNK" to "yes". You do this by just assigning the new value to the variable of the third array element. The last statement sends the value of the third element to the browser. You do not necessarily have to assign the value of an array element to a new variable, as done in the previous code in order to use (print) it. You can use (print) it directly, as done in this code.

The Length of an Array
The length of an array is the number of elements in the array. The length of all the above arrays is 10. However, the highest index of the arrays is 9. To determine the length of an array, you have to assign the array variable with its @ character to a new variable, with the $ character, then you use (print) the new variable. If you use (print) the array variable, directly you would have all the elements of the array displayed.

The following statement displays the length of the array in the code as 10. It first of all displays all the elements of the array.

use strict;

my @arr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

print @arr; print "\n";

my $arrLength = @arr;

print $arrLength;

The first and second statements are as usual. The third statement creates an array with its elements at the same time. The third line actually has two statements. You can have more than one statement in one line; all you have to do is to separate them with semicolons. The first of these statements is “print @arr;”. Since the variable of this array has the @ character, it would print all the elements (values) of the array. This list is printed without the commas. Next to this statement is ‘print "\n";’. We want the next output to the console to be in the next line, so this statement sends the newline instruction as a string (in quotes) to the console.

The next statement (last-but-one) assigns the array with the @ character to a new variable with the $ character. Variables with the $ character are for simple values (literals). Since the receiving variable has the $ character, it receives but the length of the array and not the elements (values) of the array. The last statement prints (sends to console) the value of the $arrLength variable, which is the length of the array.

Last Element Index
The index (not the value) of each of the last element of the above arrays is 9. In many cases, you usually do not know the number of elements in an array, so as to know the last index (by subtracting 1). The syntax to obtain the index of the last element of an array is

    $#arrayName

Note the preceding, $#. The following code displays the index of the last element of an array:

use strict;

my @arr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

print $#arr;

If you try the above code, you will have 9 at the browser.

Slicing an Array
Slicing an array means obtaining the values of a range of elements in an array. To do this, you begin with the @ sign. This is followed by the name of the array; then square brackets. Inside the square brackets, you begin with the index of the start element of the range, then two dots and then the index of the end element of the range. Here, a range means consecutive elements in an array. If the number of elements in the range is small, say two, three or four, then you can type their indices in the square brackets separating them with commas and you would not need the two dots.

@arr[0,1] obtains the values of the elements at index 0 and 1 from the array, @arr. @arr[3..8] obtains the values of the array elements from index 3 to 8 inclusive (including those for 3 and 8). @arr[14..$#arr] obtains the values of the array elements from index 14 to the end of the array, where $#arr means the last index of the array for @arr.

Read and try the following code:

use strict;

my @arr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

print @arr[0,1,2]; print "\n";
print @arr[2..6]; print "\n";
print @arr[5..$#arr];

If you had tried the above code, you would have noticed that the displayed values are not separated by commas. Do not worry about that for now.

Slicing can actually be more complex than this. Precisely, you can slice discontinued ranges from an array. For this basic tutorial, we shall not go into that.

Array Functions
A function is a piece of code that accomplishes a task for you. You can write your own functions. The Perl  interpreter comes with some functions already written for you, just to use. Some of these functions are used with arrays. In Perl, functions are called subroutines. We learn the array functions, now.

The push Function
Consider the array,

@hisArr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

The name of the array here is @hisArr. Also consider the list,

("xxx", "yyy", "zzz")

In Perl a list is given in normal brackets. You can append (add to the end) the three elements (values) of the list to the array. The syntax to do this is:

    push (ARRAY, LIST)

In our example, you would have,

    push (@hisArr, ("xxx", "yyy", "zzz"));

Read and try the following code:

use strict;

my @hisArr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

push (@hisArr, ("xxx", "yyy", "zzz"));

print @hisArr;

The output of the above code shows the appended list. Well, the items of the output are not separated by commas. Do not worry about that for mow. The push function returns the new number of elements in the resulting array.

The unshift Function
The unshift function does the opposite of the push function. It prepends a list in front of an array, returning the new number of elements in the resulting array. The syntax is:

    unshift (ARRAY, LIST)

In our case, you would have,

    unshift (@hisArr, ("xxx", "yyy", "zzz"));

Read and try the following code,

use strict;

my @hisArr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

unshift (@hisArr, ("xxx", "yyy", "zzz"));

print @hisArr;

The pop Function
The pop function removes the last element from the array and returns it, shortening the original array by one element. The syntax is,

    pop (ARRAY);

In our case, you would have,

    pop (@hisArr);

Read and try the following code:

use strict;

my @hisArr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

my $returnValue = pop (@hisArr);

print $returnValue; print "\n";
print @hisArr;

The fourth statement above, pops of the last element from the array assigning the value removed to the new variable, $returnValue. The last-but-one line displays the returned (removed) value. The last line displays the original array, which is now missing its last element.

The shift Function
The shift function does the opposite of the pop function. It removes the first element from the array and returns it, shortening the original array by one element. The syntax is

    shift (ARRAY);

In our case, you would have,

    shift (@hisArr);

Read and try the following code:

use strict;

my @hisArr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

my $returnValue = shift(@hisArr);

print $returnValue; print "\n";
print @hisArr;

The space between any function name and its opening bracket is optional. In the previous case, there is a one space character between pop and (. In the above case, there is no space character between shift and (; it is optional.

The splice Function
The splice function removes a portion (range) of elements from the array and replaces them with that of some list, if it is present. The resulting array may be larger or smaller than the original array depending on how many elements are in the replacement list. If there is no list, then the resulting array is shorter. The splice function returns the removed list. The syntax is,

    splice (ARRAY, OFFSET, LENGTH, LIST)

ARRAY is the name of the original array. OFFSET is the index at which the removal will start. Remember, index counting begins from zero. LENGTH is the number of consecutive elements to be removed. LIST, if present has the elements to replace the ones removed.

For our example, imagine that you want to remove 3 elements beginning from index 5 (which is position 6) and replace them with the list, ("xxx", "yyy", "zzz"). The splice function would be,

    splice (@hisArr, 5, 3, ("xxx", "yyy", "zzz"));

Read and try the following code:

use strict;

my @hisArr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

print splice (@hisArr, 5, 3, ("xxx", "yyy", "zzz")); print "\n";

print @hisArr;

The third line has the splice function. This statement for the splice function is preceded by the command (another function), which is “print”. The splice function returns the removed list. From the splice statement, as the return list is returned, it is printed (displayed) by the print function. The last line in the code displays the resulting original array. Remember, if the list is not present in the splice function, the resulting original array would not have a replacement.

The use of the splice function can be more complicated than what I have explained. For this basic tutorial, let us allow things like this.

Replacing List as Array for push Function
In all the functions we have had list consisting of elements, delimited brackets. You can replace a list with an array. Read and try the following code:

use strict;

my @hisArr = ("HBWE", "FGTR", "HTNK", 4587, 4526, 4053, "AB12", "GB58", "TG45", "RE69");

my @herArr = ("xxx", "yyy", "zzz");

push (@hisArr, @herArr);

print @hisArr;

The third line creates a new array (list) that is to be appended by the push function. The fourth line has the push function and in place of a list of elements, it has the array variable. The last line prints the resulting array.

We have done a lot. Let us take a break and continue in the next part of the series.

Chrys

Related Links

Perl Basics
Perl Data Types
Perl Syntax
Perl References Optimized
Handling Files and Directories in Perl
Perl Function
Perl Package
Perl Object Oriented Programming
Perl Regular Expressions
Perl Operators
Perl Core Number Basics and Testing
Commonly Used Perl Predefined Functions
Line Oriented Operator and Here-doc
Handling Strings in Perl
Using Perl Arrays
Using Perl Hashes
Perl Multi-Dimensional Array
Date and Time in Perl
Perl Scoping
Namespace in Perl
Perl Eval Function
Writing a Perl Command Line Tool
Perl Insecurities and Prevention
Sending Email with Perl
Advanced Course
Miscellaneous Features in Perl
Perl Two-Dimensional Structures
Advanced Perl Regular Expressions
Designing and Using a Perl Module
More Related Links
Perl Mailsend
PurePerl MySQL API
Perl Course - Professional and Advanced
Major in Website Design
Web Development Course
Producing a Pure Perl Library
MySQL Course

BACK NEXT

Comments

Become the Writer's Fan
Send the Writer a Message