An array is an ordered and mutable list of scalars. In Perl, scalars are defined as a single unit of data such as an integer, a floating-point, a character, a string, and so on. They are preceded by a $
when defined.
The array variable begins with an @
sign. We can declare an array in the following way:
@names = ("Jacob", "Kumar", "Dinesh");
Perl does not require us to declare a variable before using it. So, we can directly store the value in it.
We can access the elements in the array by indexing which works in the following way:
@order_nums = (1, 3, 55);@names = ("Jacob", "Kumar", "Dinesh");print "\$order_nums[0] = $order_nums[0]\n";print "\$order_nums[1] = $order_nums[1]\n";print "\$order_nums[2] = $order_nums[2]\n";print "\$names[0] = $names[0]\n";print "\$names[1] = $names[1]\n";print "\$names[2] = $names[2]\n";
We use the
$
sign to access elements of the array since the element is a scalar variable.
Perl provides a shortcut to define sequential arrays consisting of numbers and letters. Rather than typing to 100, we can use the ...
notation as follows:
@range_100 = (1..100);@range_abc = (a...g);print "@range_100\n";print "@range_abc\n";
The size of an array can be computed using the scalar context on the array. We can see this here:
@range_100 = (1..100);print "Size: ",scalar @range_100,"\n";
We can insert and remove elements from an array by using the following methods:
Operation | Description |
---|---|
push |
It adds the element at the end of the array. |
pop |
Removes and returns the last element of the array. |
shift |
Removes and returns the first element of the array with shifting the remaining array. |
unshift |
Adds a new element at the beginning of the array and returns the size of the resulting array. |
Let us execute these operations in the following example:
@cars = ("Honda","Toyota","Hyundai");print "1. \@cars = @cars\n";# pushing an elementpush(@cars, "Tesla");print "2. \@cars after push = @cars\n";# adding an element at beginning of the arrayunshift(@cars, "Ford");print "3. \@cars after unshift = @cars\n";# popping an element.pop(@cars);print "4. \@cars after popping = @cars\n";# removing an element from the beginning of the array.shift(@cars);print "5. \@cars after shift = @cars\n";
Free Resources