Perl: Get certain elements of an array the lazy way

I learned that you can extract various elements from a Perl array in a very creative/simple way. Using this syntax may simplify some of your code and save you a lot of time.

my @colors = ("red", "blue", "green", "yellow", "orange", "purple");

my @w = @colors[(0, 3)];    # ("red", "yellow");
my @x = @colors[(0, 2, 4)]; # ("red", "green", "orange");

# First and last element
my @y = @colors[(0, -1)];   # ("red", "purple");

# First ten items
my @z = @array[0 .. 10];    # Using the `..` range operator

Basically any call to an array where the payload is an array of indexes will return a new array with those items extracted.

my @colors = ("red", "blue", "green", "yellow", "orange", "purple");

# You can also use an array variable to specify the elements to extract
my @ids = (1,3,5);
my @x   = @colors[@ids]; # ("blue", "yellow", "purple")

Note: Since you are referencing the whole array (not one element) you use the @ sigil instead of $.



Note: Replies will be formatted with PHP Markdown Extra syntax.

Name: Email (Not Required):
 
Logged IP: 3.147.51.75
To prevent spam please submit by clicking the kitten: