Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a slice from an array reference?

Tags:

perl

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 ? 
like image 387
Sachin Avatar asked Apr 23 '10 16:04

Sachin


People also ask

How do you slice an object from an array?

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.

Can you use slice on array?

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.

How can we slice an array in C language?

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.


2 Answers

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]; 
like image 174
brian d foy Avatar answered Sep 28 '22 02:09

brian d foy


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]]; 
like image 24
Cascabel Avatar answered Sep 28 '22 00:09

Cascabel