Let us say that we have following array:
my @arr=('Jan','Feb','Mar','Apr'); my @arr2=@arr[0..2];
How can we do the same thing if we have array reference like below:
my $arr_ref=['Jan','Feb','Mar','Apr']; my $arr_ref2; # How can we do something similar to @arr[0..2]; using $arr_ref ?
Array.prototype.slice() The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end ( end not included) where start and end represent the index of items in that array. The original array will not be modified.
The slice() method can be used to create a copy of an array or return a portion of an array. It is important to note that the slice() method does not alter the original array but instead creates a shallow copy.
Run a for loop the position entered by user times, in which the element is one by one shifted towards left, and the leftmost element (i.e the first element of the array) is shifted to the nth position of the array.
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];
Just slice the reference (the syntax is similar to dereferencing it, see the comments), and then turn the resulting list back into a ref:
my $arr_ref2=[@$arr_ref[0..2]];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With