1

Consider the following lines of code. I want to slice the array ref $a and return the result as an array ref assigned to $b. I can do that in two lines as shown. I am stumped in my attempts to do this in one line! How can this be done?

$a = [1,2,3,4,5];
###the desired result###########################
@b = @{$a}[1 .. @{$a} - 1];
$b = \@b; # $b is [2,3,4,5]
################################################
###trying to get the desired result in one line##
$b = \@{$a}[1 .. @{$a} - 1]; # $b is \5;
$b = \{@{$a}[1 .. @{$a} - 1]}; # $b is \{ 2 => 3, 4 => 5 }
$b = $a->[1 .. @{$a} - 1]; # $b is 1
$b = $a->@[1 .. @{$a} - 1]; # $b is 5
3
  • 3
    Side note: avoid using $a and $b specifically even as examples, as they are special globals for the sort function - it either bypasses the typo-checking benefits of strict 'vars', or if you declare them lexically, breaks sort calls in that scope. I suggest $x/$y Commented Apr 15, 2019 at 23:21
  • The reason why your attempts are not valid ways to create a reference are because you cannot reference a slice of an array, you must reference a full array. Thus you must create a new array reference, with copies of the sliced elements, as shown in the answers. Commented Apr 15, 2019 at 23:24
  • 2
    Also, if you want to modify the array in place rather than create a new one, the splice function may be useful (it also works on dereferenced arrayrefs). Just take care that this is really what you want. Commented Apr 15, 2019 at 23:43

2 Answers 2

4

you can say

$b = [ @{$a}[1 .. @{$a} - 1] ];
Sign up to request clarification or add additional context in comments.

Comments

2

Inspired by this question, there is also

$b = [ splice @{[@$a]},1 ]

1 Comment

splice @{$b = [@$a]}, 0, 1 would create only one copy, as the other solutions do.

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.