Perl | Array Slices
Last Updated :
26 Nov, 2019
Improve
In Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable.
Arrays can store any type of data and that data can be accessed in multiple ways. These values can be extracted by placing $ sign before the array and storing the index value of the element to be accessed within the square brackets.
For Example:
Perl
This method of extracting array elements can be used only to extract one element at a time, which might become confusing when there is a long list of elements to be accessed. For Example, if the list contains 100 elements and we need to extract 20 elements from Index 'a' to Index 'b', then this method will create a confusion. In order to avoid such kind of situation, Perl provides a method of array slicing. This can be used to access a range of array elements.
Array slicing is done to access a range of elements in an array in order to ease the process of accessing a multiple number of elements from the array. This can be done in two ways:
Perl
Perl
# Define an array
@arr = (1, 2, 3);
# Accessing and printing first
# element of an array
print "$arr[0]\n";
# Accessing and printing second
# element of an array
print "$arr[1]\n";
Slicing of an Array
- Passing multiple index values
- Using range operator
#!/usr/bin/perl
# Perl program to implement the use of Array Slice
@array = ('Geeks', 'for', 'Geek');
# Using slicing method
@extracted_elements = @array[1, 2];
# Printing the extracted elements
print"Extracted elements: ".
"@extracted_elements";
Output:
This method of passing multiple indexes becomes a bit complicated when a large number of values are to be accessed.
Using Range Operator
Range operator[..] can also be used to perform the slicing method in an array by accessing a range of elements whose starting and ending index are given within the square brackets separated by range operator(..). This method is more feasible as it can print elements within a long range of elements, as compared to passing multiple parameters.
Example:
Extracted elements: for Geek
#!/usr/bin/perl
# Perl program to implement the use of Array Slice
@array = ('Geeks', 'for', 'Geek', 'Welcomes', 'You');
# Using range operator for slicing method
@extracted_elements = @array[1..3];
# Printing the extracted elements
print"Extracted elements: ".
"@extracted_elements";
Output:
This method of slicing the Array to access elements is used widely to perform multiple operations on the array. Operations like, pushing elements, printing elements of array, deleting elements, etc.
Extracted elements: for Geek Welcomes