sail0r
sail0r

Reputation: 451

how to slice am array ref and return an array ref in one line?

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

Upvotes: 1

Views: 86

Answers (2)

Michael Quaranta
Michael Quaranta

Reputation: 118

you can say

$b = [ @{$a}[1 .. @{$a} - 1] ];

Upvotes: 4

mob
mob

Reputation: 118605

Inspired by this question, there is also

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

Upvotes: 2

Related Questions