Node:It Slices!, Next:, Previous:Manipulating Arrays and Lists, Up:Manipulating Arrays and Lists



It Slices!

Sometimes, you may want to create a new array based on some subset of elements from another array. To do this, you use a slice. Slices use a subscript that is itself a list of integers to grab a list of elements from an array. This looks easier in Perl than it does in English:

     use strict;
     my @stuff = qw/everybody wants a rock/;
     my @rock  = @stuff[1 .. $#stuff];      # @rock is qw/wants a rock/
     my @want  = @stuff[ 0 .. 1];           # @want is qw/everybody wants/
     @rock     = @stuff[0, $#stuff];        # @rock is qw/everybody rock/
     

As you can see, you can use both the .. operator and commas to build a list for use as a slice subscript. This can be a very useful feature for array manipulation.