3.1.7 Accessing a Slice of Elements from an Array

In addition to accessing a single element from an array, it is possible to access several elements in one shot. Such a sequence of elements is called a slice. If @friends has elements with index 4 and 20 defined, and we want to extract these elements, we can write

@selectFriends = @friends [4,20];

A slice produces a sequence of elements and hence is a list or a vector by itself. Therefore, when we use a slice on the right hand side of an assignment, the target of the assignment must be a list or a vector itself. In obtaining the slice, the indices of the selected elements are separated by comma.

In obtaining a slice from a list or a vector, we can use the double dot operator between integers to specify a range of indices. To obtain the slice containing elements with indices 0,2,3,4, and 20 we can write

@selectFriends = @friends [0, 2..4, 20];

2..4 expands to a list containing 2,3 and 4.

We can access an element or a slice from an array literal also. A literal is one in which the values are specified explicitly.

$firstFriend = ('Jeff Luvellis', 'Brett Walters', 'Justin OMalley', 'Aaron Sturtevent') [0];

@selectFriends = ('Jeff Luvellis', 'Brett Walters', 'Justin OMalley', 'Aaron Sturtevent') [1,3];