How do I get a slice from an array reference?

To get a slice starting with an array reference, replace the array name with a block containing the array reference. I’ve used whitespace to spread out the parts, but it’s still the same thing:

 my @slice =   @   array   [1,3,2];
 my @slice =   @ { $aref } [1,3,2];

If the reference inside the block is a simple scalar (so, not an array or hash element or a lot of code), you can leave off the braces:

 my @slice =   @$aref[1,3,2];

Then, if you want a reference from that, you can use the anonymous array constructor:

 my $slice_ref = [ @$aref[1,3,2] ];

With the new post-dereference feature (experimental) in v5.20,

use v5.20;
use feature qw(postderef);
no warnings qw(experimental::postderef);

my @slice = $aref->@[1,3,2];

Leave a Comment

tech