Perl Programming Page 8 - Array Manipulation in Perl |
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:
Or how about this one?
You can also use a negative index for the "start" position, to force Perl to begin counting from the right instead of the left.
Perl also comes with a range operator (..) which provides an alternative way of extracting array slices. Here's an example:
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:
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:
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. Here's an example:
blog comments powered by Disqus |