Arrays and their Operations
Let's learn how to access the contents of an array and learn how to use built-in methods in this lesson.
As we discussed earlier, an array is like a list of values. The simplest form of an array is indexed and ordered by an integer starting with index 0.
Note: To debug your code while working with arrays, it is very important to view the keys and their associated values. Accessing the length of an array can also be useful on numerous occasions.
Outputting a structured view of arrays
To print an array in a readable format, we use the following statement:
print "@arrayName";
This statement will print the contents of the array separated, by a space. Run the code below to see how print works with arrays.
The .. operator
The .. operator is used to represent a range to initialize an array. For example, the “1 .. 8” range populates an array with values from “1 to 8”. Let’s look at a code example that uses the .. operator:
pop and push subroutines
The array in Perl can be used to implement a stack. The end of the array acts as the top of the stack, where push and pop operations take place to add and remove elements to and from the stack, respectively.
The push subroutine takes two arguments:
- The name of the array.
- The element to be pushed.
The pop subroutine takes only one argument, i.e., the name of the array.
Let’s explore both of these operations in the following code:
shift and unshift subroutine
The shift and unshift subroutines also help to implement the behavior of a stack, using the starting point of an array as the top of the stack.
The shift subroutine takes the name of the array as the argument and removes the first element from the array.
The unshift subroutine adds a new element at the start of the array and takes two arguments:
- Name of the array.
- Element to be added.
Let’s explore both of these operations in the following code:
Length of an array
The total number of elements in an array is called the length of an array. This length is dynamic and can change over time. The scalar subroutine is used to find the length of the array. It takes the name of the array as the argument. Let’s see how it works in the following code:
Accessing element at a specific index
We often need to access an element at a specific index in an array. In Perl, $arr[3] accesses the element at index 3 in the array named arr. In addition, $#arr refers to the currently highest index in the array arr. Let’s look at the example: