Over the course of this tutorial, I'll be examining Perl's arrays in detail, explaining what they are, how they work, and how you can use them to get things done faster, better and cheaper. In addition to providing a gentle introduction to Perl arrays and hashes in general, this article will also offer you a broad overview of Perl's array manipulation functions, providing you with a handy reference that should help you write more efficient code.
Perl allows you to extract a subsection of an array - a so-called "array slice" - simply by specifying the index values needed in the slice. Consider the following example:
# extract elements 2 to 5 # slice contains "blue", "yellow", "orange", "violet" @slice = @rainbow[2..5];
You can also use the range operator to create arrays consisting of all the values in a range. For example, if you wanted an array consisting of the numbers between 1 and 20 (both inclusive), you could use the following code to generate it automatically:
#!/usr/bin/perl # define array @n = (1..20);
The splice() function allows you to delete a specified segment of an array and splice in one or more values to replace it. Here's what it looks like:
splice
(array, start, length, replacement-values)
where "array" is an array variable, "start" is the index to begin slicing at, "length" is the number of elements to remove from "start", and "replacement-values" are the values to splice in.