tags:

views:

101

answers:

3

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 ?
+6  A: 

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]];
Jefromi
that's not what that does. `@$ref[...]` is an array slice using a reference; there is no intermediate array generated.See http://perlmonks.org?node=References+quick+reference
ysth
oh, maybe by "resulting array" you mean what's generated by the array slice? That's not an array, it's a list.
ysth
@ysth: My bad, updated.
Jefromi
@ysth: Surely it's not misleading to think of an array slice using reference as slicing the array which is the result of dereferencing the reference?
Jefromi
It's bad to make people think `@$ref[...]` is as inefficient as `(@$ref)[...]`
ysth
@ysth: Ah, okay. Thanks!
Jefromi
Remember the difference between a list an an array: http://www.effectiveperlprogramming.com/blog/39 :)
brian d foy
@Jefromi: Thank you very much
Sachin
+3  A: 
my $arr_ref2 = [ @$arr_ref[0..2] ];
DVK
+2  A: 

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] ];
brian d foy