Array and Hash Slices

In addition to all the operations you learned about on Days 4, “Working with Lists and Arrays,” and 5, “Working with Hashes,” Perl also has a mechanism for copying some subset of elements from the collection. That's called a slice—a subset of an array or a hash that is, in turn, another array or hash.

You take a slice of an array similarly to how you access one element: using brackets. However, there are two significant differences between a slice and a single element. Here are some lines of Perl code that show the syntax for slices:

@array = (1,2,3,4,5);
$one = $array[0];     # $one is 1
@slice = @array[0,1,2];  # @slice is (1,2,3)

See the differences? In the element access expression $array[0], you use a $ to refer to the ...

Get Sams Teach Yourself Perl in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.