Learning Perl - Arrays


Learning Perl - Arrays


As stated in the previous post, Perl has three types of variables: scalars, arrays and hashes. Today we are going to explore arrays in more detail.

What is an array?

An array is a list of scalars, aka a list of single values whether this is strings, numbers or references it does not matter. An array is a variable that can hold multiple values of different types. In Perl, arrays are denoted by the @ symbol and like shown in the other post can be declared using a 'my' keyword. They can be accessed a few different ways, but the most common way is to use the index of the element you want to access. The index starts at 0, so the first element of an array is at index 0, the second element is at index 1, and so on. However you can also use negative indices to access elements from the end of the array, where -1 is the last element, -2 is the second to last, and so on. You can also slice access an array to select a range of elements. You can use the following table as a reference to how you can access elements in an array:

Syntax Description
@array1 The array itself
$array[0] The first element of the array
$array[-1] The last element of the array
$#array The index of the last element of the array
@array[0..3] The first four elements of the array
@array[0,2,4] The first, third and fifth elements of the array
@array[0..$#array] All elements of the array
@array[0..$#array-1] All elements of the array except the last one

In the previous post we have already seen how to declare an array using the 'my' keyword, like so:

my @array = (1, 2, 3, 4, 5);
Enter fullscreen mode Exit fullscreen mode

This code declares an array called '@array' and initialises it with five scalar values. You can also declare an array without initialising it, like so:

my @array;
Enter fullscreen mode Exit fullscreen mode

You can then add elements to the array later using one of the keywords I will explain next or by assigning values to specific indices. To assign values to specific index of an array, you can use the following syntax:

$array[0] = 100; # Assigns 100 to the first element of the array
Enter fullscreen mode Exit fullscreen mode

So arrays in perl also have several other keywords that can be used to to access, modify, and manipulate the contents of them once they have been instantiated. The following table can be used as a reference:

Keyword Description
splice(@array, 2, 3) Removes three elements starting at index 2
push(@array, $value) Adds a value to the end of the array
pop(@array) Removes the last element of the array
shift(@array) Removes the first element of the array
unshift(@array, $value) Adds a value to the beginning of the array
sort(@array) Sorts the array in ascending order
reverse(@array) Reverses the order of the array
join(',', @array) Joins the elements of the array into a string, separated by commas
split(',', $string) Splits a string into an array, using commas as the delimiter
grep { $_ > 10 } @array Filters the array, keeping only elements greater than 10
map { $_ * 2 } @array Applies a transformation to each element of the array, doubling its value
scalar(@array) Returns the number of elements in the array

Today we will explore these keywords in more detail, and show how they can be used in practice. Lets create a new file called 'arrays.pl' and add the following code to it:

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
# Declare an array
my @array = (1, 2, 3, 4, 5);
# Print the array
print "Original array: ", Dumper(\@array);
Enter fullscreen mode Exit fullscreen mode

This code should be familiar to you as we have declared an array in our previous post. What is new is the use of the 'Data::Dumper' module, which is a Perl module that allows you to print complex data structures in a human-readable format. This is useful for debugging and understanding the contents of your variables. We also use the 'print' keyword instead of the feature 'say', this means to get new lines we have to explicitly add the new line character "\n" unless the last parameter is Dumper which will add this for us.

If we now run this code, we should see the following output:

Original array: $VAR1 = [
          1,
          2,
          3,
          4,
          5
        ];
Enter fullscreen mode Exit fullscreen mode

Now that we have our array declared, we can start using some of the keywords we mentioned earlier. Let's explore them in more detail. Update at the end of your file the following:

# Add a value to the end of the array
my $push = push(@array, 6);
# Print the array after adding a value
print "After push: ", Dumper(\@array);
print "Pushed value: $push\n"; # length
Enter fullscreen mode Exit fullscreen mode

When we run this code, we should see the following additional output:

After push: $VAR1 = [
          1,
          2,
          3,
          4,
          5,
          6
        ];
Pushed value: 6
Enter fullscreen mode Exit fullscreen mode

Now we have added a new element to the end of the array using the 'push' keyword. It's important to understand the push keyword returns the count of total number of items in the array and you can push many items at once. Next, let's remove the last element of the array using the 'pop' keyword to restore our array to what we originally defined. Add the following code to your file:

# Remove the last element of the array
my $pop = pop(@array);
# Print the array after removing the last element
print "After pop: ", Dumper(\@array);
print "Popped value: $pop\n";
Enter fullscreen mode Exit fullscreen mode

With that in place when we run this code, we should see the following additional output:

After pop: $VAR1 = [
          1,
          2,
          3,
          4,
          5
        ];
Popped value: 6
Enter fullscreen mode Exit fullscreen mode

Next let's remove the first element of the array using the 'shift' keyword. Add the following code to your file:

# Remove the first element of the array
my $first = shift(@array);
# Print the array after removing the first element
print "After shift: ", Dumper(\@array);
print "Shifted value: $first\n";
Enter fullscreen mode Exit fullscreen mode

When we run this code, we should see the following additional output:

After shift: $VAR1 = [
          2,
          3,
          4,
          5
        ];
Shifted value: 1
Enter fullscreen mode Exit fullscreen mode

Now we have removed the first element of the array using the 'shift' keyword. Next, let's add the element we shifted back to the beginning of the array using the 'unshift' keyword. Add the following code to your file:

# Add a value to the beginning of the array
my $unshift = unshift(@array, $first);
# Print the array after adding a value to the beginning
print "After unshift: ", Dumper(\@array);
print "Unshifted value: $unshift\n"; # length
Enter fullscreen mode Exit fullscreen mode

When we run this code, we should see the following additional output:

After unshift: $VAR1 = [
          1,
          2,
          3,
          4,
          5
        ];
Unshifted value: 5
Enter fullscreen mode Exit fullscreen mode

It's important to understand the unshift keyword returns the count of total number of items in the array and you can unshift many items at once. With that working let's reverse the order using the 'reverse' keyword. Add the following code to your file:

# Reverse the order of the array
my @reversed = reverse(@array);
# Print the reversed array
print "Reversed array: ", Dumper(\@reversed);
Enter fullscreen mode Exit fullscreen mode

This has created a copy of the array and reversed the order when we run our script we should get the following additional output:

Reversed array: $VAR1 = [
          5,
          4,
          3,
          2,
          1
        ];
Enter fullscreen mode Exit fullscreen mode

With the order reversed lets put it back to the original order but this time using sort (and yes in this example you could just use reverse again):

# Sort the array in ascending order
my @sorted = sort { $a <=> $b } @reversed;
# Print the sorted array
print "Sorted array: ", Dumper(\@sorted), "\n";
Enter fullscreen mode Exit fullscreen mode

Okay so the syntax here is a little more complicated, sort accepts a code reference { ... } and then an array to sort. The '$a' and '$b' are special variables that represent the two elements being compared. The '<=>' operator is the numeric comparison operator, which returns -1, 0, or 1 depending on whether the first element is less than, equal to, or greater than the second element. Do not worry if you do not fully follow, I will explain in more detail what code references are in a future post. If we run the code, we should see the following additional output:

Sorted array: $VAR1 = [
          1,
          2,
          3,
          4,
          5
        ];
Enter fullscreen mode Exit fullscreen mode

We have sorted the array in ascending order. Next, let's join the elements of the array into a string using the 'join' function. Add the following code to your file:

# Join the elements of the array into a string
my $joined = join(',', @sorted);
# Print the joined string
print "Joined string: $joined\n";
Enter fullscreen mode Exit fullscreen mode

When we run this code, we should see the following additional output:

Joined string: 1,2,3,4,5
Enter fullscreen mode Exit fullscreen mode

Now we have joined the elements of the array into a string, separated by commas. Next, let's split a string into an array using the 'split' function. Add the following code to your file:

# Split a string into an array
my $string = "apple,banana,cherry";
my @split_array = split(',', $string);
# Print the split array
print "Split array: ", Dumper(\@split_array);
Enter fullscreen mode Exit fullscreen mode

and again run your script and you should see this additionally:

Split array: $VAR1 = [
          'apple',
          'banana',
          'cherry'
        ];
Enter fullscreen mode Exit fullscreen mode

Next, let's filter an array using the 'grep' function. Add the following code to your file:

# Filter the array, keeping only elements greater than 2
my @filtered = grep { $_ > 2 } @sorted;
# Print the filtered array
print "Filtered array: ", Dumper(\@filtered), "\n";
Enter fullscreen mode Exit fullscreen mode

When we run this code, we should see the following additional output:

Filtered array: $VAR1 = [
          3,
          4,
          5
        ];
Enter fullscreen mode Exit fullscreen mode

The 'grep' keyword works differently to 'sort', it still expects a code reference but instead of comparing two elements, it applies the code to each element in the array. If the item meets the condition then it is copied into the new array. Here we are checking if the number is greater than 2. Next let's apply a transformation to each element of the array using the 'map' function. Add the following code to your file:

# Apply a transformation to each element of the array, doubling its value
my @mapped = map { $_ * 2 } @filtered;
# Print the mapped array
print "Mapped array: ", Dumper(\@mapped), "\n";
Enter fullscreen mode Exit fullscreen mode

When we run this code, we should see the following additional output:

Mapped array: $VAR1 = [
          6,
          8,
          10
        ];
Enter fullscreen mode Exit fullscreen mode

The 'map' keyword works similarly to the 'grep' keyword but instead of filtering by the code reference we transform/manipulate the value which is then copied into the new array. Finally, let's check the number of elements in the array using the 'scalar' function. Add the following code to your file:

# Check the number of elements in the array
my $count = scalar(@mapped);
# Print the number of elements in the array
print "Number of elements in mapped array: $count\n";
Enter fullscreen mode Exit fullscreen mode

When we run this code, we should see the following additional output:

Number of elements in mapped array: 3
Enter fullscreen mode Exit fullscreen mode

In a future post, we’ll take a closer look at how to iterate over arrays and how they can be used within more complex data structures. For now, we’ve covered just the basics, but I hope this has helped you get a better understanding of how arrays work in Perl. Next time, we’ll explore hashes in more detail. Until then, if you have any questions or comments, feel free to share them below.

Related Blogs

Learning Perl – Introduction
Perl has long been known as the “duct tape of the Internet,” or "the Swiss Army chainsaw of scripting...
Learning Perl - Variables
I will attempt to explain things in this post in a way that is easy to understand, even for those who...
Learning Perl - Hashes
In the last post we covered the basics of arrays, today we will look at hashes in more detail. What...
Learning Perl - Conditional Statements
So far we have covered basic variables in Perl, today we are going to look at how to use these...
Learning Perl - Loops and Iteration
In previous posts, we explored variables, arrays, hashes, and conditional statements in Perl. Now...
Learning Perl - Scalars
Before moving onto more complex topics lets come back to how we represent data in Perl. The most...
Learning Perl - References
In the last post we learnt how to create a reference to a scalar, an array, and a hash. In this post,...
Learning Perl - Ternary Operators
In a previous post, we learned about conditional statements in Perl. The ternary operator is an...
Learning Perl - Subroutines
Subroutines are one of the most important building blocks in programming. They allow you to organise...
Learning Perl - Regular Expressions
Regular expressions also known as regex or regexp, are a powerful way to match patterns in text. Most...
Learning Perl - Modules
A module in Perl is a reusable piece of code that can be included in your scripts to provide...
Learning Perl - CPAN
In the last post I showed you how to create a new module and how to use it in your code. In this post...
Learning Perl - Plain Old Documentation
When you write and program in any language it is good practice to document your code. Each language...
Learning Perl - Testing
In this post we will look at how to test Perl code using the Test::More module. Like documentation,...
Learning Perl - Exporting
In programming, we often want to share functionality across different parts of our code. In Perl,...
Learning Perl - Object Orientation
Object-Oriented Programming (OOP) is a widely used programming paradigm that enables the creation of...
Learning Perl - Inheritance
In the last post we discussed Object Oriented Programming in Perl, focusing on the basics of creating...
Learning Perl - File Handles
In programming file processing is a key skill to master. Files are essential for storing data,...
Learning Perl - Prototypes
Today we are going to discuss Perl subroutine prototypes, which are a way to enforce a certain...
Learning Perl - Overloading Operators
In the last post we investigated prototype subroutines in Perl. In this post, we will look at...