As we learned in the previous lessons, an array is simply a list of scalars. The list can contain any scalars and has a definite order.
To access a particular element of an array, you can use the array subscript syntax like this:
How are elements of an array accessed in Perl?
In Perl, elements of an array are accessed using their index, which is a non-negative integer. Array indexes start at 0 for the first element, 1 for the second element, and so on. To access individual elements of an array, you use the dollar sign ($) prefix followed by the array name and the index of the element enclosed in square brackets ([]).
Here's the syntax for accessing elements of an array in Perl:
$array_name[index]
Here's an example demonstrating how to access elements of an array:
my @fruits = ('apple', 'banana', 'cherry', 'orange');
# Accessing elements using their index
print $fruits[0]; # Output: apple
print $fruits[1]; # Output: banana
print $fruits[2]; # Output: cherry
print $fruits[3]; # Output: orange
You can also access elements from the end of the array using negative indexes:
Keep in mind that accessing an array element with an index that is out of bounds will not result in an error but will return undef, which is Perl's way of representing an undefined value:
print $fruits[10]; # Output: (nothing, since the value is undef)
To modify the value of an array element, you can assign a new value to that element using its index:
In summary, elements of an array in Perl are accessed using their index, starting from 0. You can access and modify the elements by using the $ prefix, the array name, and the index enclosed in square brackets.
The subscript, sometimes also called the index, is the number in the brackets ([0]).
The first member of the array ("dave") is element number zero. You will also notice that the $ is used to access the array, because the member of the array is a scalar. In the next lesson, subscripts will be examined in more detail.