Array Manipulation in Perl - Slice and Dice (Page 8 of 9 )
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:
#!/usr/bin/perl
# define array
@rainbow = ("red", "green", "blue", "yellow", "orange", "violet", "indigo");
# extract slice "blue", "yellow"
@slice = @rainbow[2,3];
Or how about this one?
#!/usr/bin/perl
# define array
@rainbow = ("red", "green", "blue", "yellow", "orange", "violet", "indigo");
# extract slice "blue", "violet", "red", "indigo"
@slice = @rainbow[2,5,0,6];
You can also use a negative index for the "start" position, to force Perl to begin counting from the right instead of the left.
#!/usr/bin/perl
# define array
@rainbow = ("red", "green", "blue", "yellow", "orange", "violet", "indigo");
# extract slice "indigo", "red"
@slice = @rainbow[-1,-7];
Perl also comes with a range operator (..) which provides an alternative way of extracting array slices. Here's an example:
#!/usr/bin/perl
# define array
@rainbow = ("red", "green", "blue", "yellow", "orange", "violet", "indigo");
# 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.
Here's an example:
#!/usr/bin/perl
# define array
@rainbow = ("red", "green", "blue");
# remove elements 1 and 2
# replace with new values
splice (@rainbow, 1, 2, "yellow", "orange");
# array now looks like this
@rainbow = ("red", "yellow", "orange");
Next: Sorting Things Out >>
More Perl Articles
More By Harish Kamath, (c) Melonfire