1

To get a sub array of an array, we can do something like:

@x = (1,2,3,4,5,6);
@y = @x[1 .. 4]

What I have reference to an array

$x = [1,2,3,4,5,6];

What is an easy way to get a reference to a sub array

$y = $x->[1 .. 4]; #doesn't work.

Thanks.

3 Answers 3

1

The equivalent of

my @x = (1,2,3,4,5,6);
my @y = @x[1..4]

is

my $x = [ (1,2,3,4,5,6) ];      (Parens can be removed)
my $y = [ @$x[1..4] ];

which is basically the same as

my @x = (1,2,3,4,5,6);   my $x = \@x;
my @y = @$x[1..4];       my $y = \@y;

There's no such thing as a sub array or a reference to one.

Sign up to request clarification or add additional context in comments.

Comments

1

I dont think that is possible the better way is to take subarray in new array and then take the reference to that new array.

@x = (1,2,3,4,5,6);
@y = @x[1 .. 4];

my $arrf = \@y
print "@$arrf";

Comments

0

An array slice isn't a variable, you can't take a reference to it. But if you want a reference to a new anonymous array created from a slice of the original array you can do

$y = [ @$x[1 .. 4] ];

where @$x[1 .. 4] slices @$x in the same way as @x[1 .. 4] slices @x, and the
[ ... ] operator creates a reference to a new array. The elements of @$y are shallow copies of the elements in @$x; modifying @$y doesn't modify @$x (but if some of those elements are references, they will still reference the same data).

1 Comment

you can get actual aliases with $y=sub{\@_}->(@$x[1..4])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.