1. Perl
  2. Operators
  3. here

Array slice

Array slice allows you to retrieve multiple elements from array by specifying the index.

# Array slice
my @values = @array[0, 3, 5];

This is an example to get the elements with indexes 1 and 3 from the array.

# Get multiple elements
my @nums = ('a', 'b', 'c', 'd');
my @choice = @nums[1, 3];

The result is that if @nums is ('a', 'b', 'c', 'd') then @choice is ('b', 'd').

To slice an array against array reference, you can do the following:

# Array slice against array reference
my $nums = ['a', 'b', 'c', 'd'];
my @choice = @$nums[1, 3];

Use array slice as lvalue

Using an array slice as an lvalue allows you to assign to multiple values with a specified index.

# Use double array slice as lvalue
my @nums = ('a', 'b', 'c', 'd');
@nums[1, 3] = ('e', 'f');

Hash slice

A similar feature to array slice is hash slice. You can get multiple values by specifying hash key.

my @math_score_slice = @math_scores{'Aiko', 'Kenta'};

Related Informatrion