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 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); 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 ]; 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 When we run this code, we should see the following additional output: After push: $VAR1 = [ 1, 2, 3, 4, 5, 6 ]; Pushed value: 6 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"; 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 Next let's remove the first element of the array using the 'shift' keyword. Add th

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 |
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);
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
];
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
When we run this code, we should see the following additional output:
After push: $VAR1 = [
1,
2,
3,
4,
5,
6
];
Pushed value: 6
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";
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
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";
When we run this code, we should see the following additional output:
After shift: $VAR1 = [
2,
3,
4,
5
];
Shifted value: 1
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
When we run this code, we should see the following additional output:
After unshift: $VAR1 = [
1,
2,
3,
4,
5
];
Unshifted value: 5
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);
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
];
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";
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
];
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";
When we run this code, we should see the following additional output:
Joined string: 1,2,3,4,5
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);
and again run your script and you should see this additionally:
Split array: $VAR1 = [
'apple',
'banana',
'cherry'
];
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";
When we run this code, we should see the following additional output:
Filtered array: $VAR1 = [
3,
4,
5
];
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";
When we run this code, we should see the following additional output:
Mapped array: $VAR1 = [
6,
8,
10
];
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";
When we run this code, we should see the following additional output:
Number of elements in mapped array: 3
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.