Perl Arrays - Learn by Examples How to Create and Manipulate them

We can define Perl arrays as having the following general characteristics:

  • they are ordered lists of scalars;
  • the variable name starts with the @ character;
  • the first element of the list has the index 0, the next has the index 1, and so on;
  • the number of array elements is unlimited;
  • an element of the array variable starts with the $ character followed by the variable name and the array element index included in square brackets;
There is an example of a Perl array variable below:

@family = ("father","mother","son","daughter");

In this instance through @family we understand the entire array and if we want to get the first element of the @family array, we use the notation $family[0]. The strings "father", "mother", "son" and "daughter" are the elements of the @family array.

Click Below to See the Best

Perl How-to Snippet Collection

and Save Hours of Surfing on Internet!

Before seeing what we can do with the Perl arrays, let’s speak a bit about context, which is an important feature of Perl Language. There are two most important Perl contexts: scalar and list. The context modifies the operators and functions behavior depending on the type of expression we have to deal with: list or scalar. Please look at these examples shown below:

@v1 = @family;
($v2)  =  @family;
$v3  = @family;
$v4 = ("father", "mother", "son", "daughter");

In the first example we have list context on the left, after assignment @v1 and @family variables will have the same content, i. e. the list ("father", "mother", "son", "daughter").

In the second example, we have also list context on the left, but the list on the left has only one element, so the scalar variable $v2 will be assigned with the first element of the @family array, i.e. "father".

In the third example, we have scalar context on the left, so after assignment $v3 it will contain the number of @family array elements (i.e. 4) – because @family was evaluated in a scalar context.

And finally, in the fourth example we have scalar context on the left, so the variable $v4 will be assigned step by step with the @family elements and at the end it will contain the last value in the list, i.e. the string "daughter".

Next I’ll show you some usual ways to create and manipulate the array variables in a Perl script.

Append elements to Perl arrays

You can use the push function to do this, like in the next example:

@colors =  ("white", "red", "yellow", "blue");
$color = "green";
$length = push(@colors, $color);

After assignment, the @colors variable will contain the list ("white", "red", "yellow", "blue", "green") and the push function will return in the $length variable the number of @colors elements after appending, i.e. the number 5.

Assign a list to Perl arrays

As seen in the examples below, you can assign a list to an array either including the list elements in quotation marks and separating them by comma, or using qw (quote word) operator when there are no whitespaces (spaces, tabs or newlines) included in the elements of the list. Perl is a straightforward language and it’s not necessary to allocate or deallocate the Perl arrays, it’s enough to assign a list to an array variable in order to get it ready to use.

@colors =  ("white", "red", "yellow", "dark gray");
@colors1 = qw(white red yellow gray);

Concatenate Perl arrays

Please take your time and have a look at the following example:

@boys = qw(John Peter Robert William);
@girls = qw(Alice Christine Sophie Mary);
@children = (@boys, @girls);
@pairs = map{"$boys[$_]-$girls[$_]"} 0..$#boys ;
$girlsNames = join(", ",@girls);

The first two lines of the code snippet initialize the @boys and @girls arrays.

The third line shows you how to concatenate two arrays, using the comma (,) operator. The @children array will contain the elements of the both arrays, without sorting them: "John", "Peter", "Robert", "William", "Alice", "Christine", "Sophie", "".

The fourth line is an example about how you can concatenate the two Perl arrays @girls and @boys by alternating their elements, getting as result the array @pairs, composed by the elements: "John-Alice", "Peter-Christine", "Robert-Sophie", "William-Mary", by using the map function.

Finally, the fifth line concatenates an array into one string, using the join function and specifying how the items will be separated – in this case by commas.

Modify Perl arrays elements

Let’s try to modify each element of a Perl array. You can do this either using the map function or the foreach loop. Look at the example below to see what I mean.

@names = qw(john alice christine william robert);
foreach (@names) {
    $_ = uc($_);
map ($_ = lc($_), @names);
@names = map {ucfirst} @names; 

The first line initializes the @names array;

The foreach loop iterates through the array elements and replaces each element (in our case a string) with the same string but in uppercase characters.

The fifth code line uses the map function to convert the array elements back to lowercase characters.

Finally, in the last line we use again the map function, but in this case the built-in function ucfirst will convert the first letter of each element of the array in upper case letters. Thus, the @names array will contain the list "John Alice Christine William Robert".

Note that we use here the both syntax forms for the map function:

@result = map expression, list 
@result = map { code } list

Please remember that the map function evaluates the expression or execute the code block for each element of the list and returns these modified elements into the @result array. For iterating through the list the $_ variable is used.

Sort Perl arrays

If you want to sort the elements of Perl arrays, there are two ways to take into consideration: sort alphabetically in ASCII order or numerically. In the both cases you must use the sort function.

By default, this function sorts the elements of an array in alphabetical order with uppercase first, like in the line of code shown below:

@sortedArray = sort (@unsortedArray);

Remember that the sort function doesn’t alter the elements of the array to be sorted, but returns a copy of the sorted array.

If you want to sort Perl arrays in a reverse alphabetical order, you can use the cmp built-in string comparison operator and the special package variables $a and $b:

sort {$b cmp $a} @array;

But if you have an array which contains a list of numbers, perhaps you want to sort it numerically. The solution is to use the <=> built-in numerical comparison operator and again the two special variables $a and $b. In this case you may sort the elements of the array in ascending or descending order:

# ascending order
@sortedArray = sort {$a <=> $b} @unsortedArray;  
# descending order
@sortedArray = sort {$b <=> $a} @unsortedArray; 
sort {$b cmp $a} @array;

Finally, you can change the order of the array elements by using the reverse function, which reverses the order of the elements stored in an array:

@array = reverse (@array); 

Now, I’ll exemplify all these through a simple short code snippet.

@gemstones = ("topaz", "diamond", "Ruby", "sapphire", 
                      "Pearl", "quartz");
@numbers = (17, 25, 13, 47, 2, 9);
@gemstones = reverse (@gemstones);
@gemstones = sort (@gemstones);
@gemstones = sort {$b cmp $a} @gemstones;
@sortedNumbers = sort {$a <=> $b} @numbers;
@numbers = sort {$b <=> $a} @numbers;

The first two lines initialize the @gemstones and @numbers arrays.

The third line reverses the order of the @gemstones array elements and the new content of the array will be the list ("quartz", "Pearl", "sapphire", "Ruby", "diamond", "topaz").

The fourth line sorts the @gemstones in an ascending alphabetical order (default) and after sorting, the array will contain the list ("Pearl", "Ruby", "diamond", "quartz", "sapphire", "topaz"). The fifth line sorts the array in an descending alphabetical order and into the array we’ll get the list ("topaz", "sapphire", "quartz", "diamond", "Ruby", "Pearl").

The next line sorts the @numbers array in an ascending numerical order and the ascending sorted list (2, 9, 13, 17, 25, 47) will be stored in a new array. The last line of the snippet code sorts the @numbers array in descending numerical order and the descending sorted list (47, 25, 17, 13, 9, 2) will be copied into the same array.

If you want to download the Perl array script with all the above examples included, please click here: Script download

A-N-Y-O-N-E Can Learn and Master Perl!
And That Includes YOU!

Check these how-to tutorial eBooks (PDF format):

Table of Contents:

A Perl Script
Install Perl
Running Perl
Perl Data Types
Perl Variables
Perl Operators
Perl Lists
Perl Arrays (more)
    Array Size
    Array Length
Perl Hashes
Perl Statements
    Perl if
    Perl unless
    Perl switch
    Perl while
    Perl do-while
    Perl until
    Perl do-until
    Perl for
    Perl foreach
Built-in Perl Functions
    Functions by Category
        String Functions
        Regular Expressions and Pattern Matching
        List Functions
        Array Functions
        Hash Functions
        Miscellaneous Functions
    Functions in alphabetical order

return to Perl Basics

Would you like to create your own website like this one?
Hit the Alarm Clock!

Site Build It!