Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking some array without looping

Tags:

arrays

perl

I'm still newbie in Perl. I'm trying to take some arrays and put them in another array without using loop.

my @array1 = ("abc", "def", "ghi", "jkl", "mno", "pqr");
my @array2=$array1[2 .. 4];

but it can't work.

I want the result of @array2 is "def ghi jkl".

like image 923
Tom Erdos Avatar asked Jul 29 '26 03:07

Tom Erdos


2 Answers

You need to use @ for array slice instead of scalar marker ($):

my @array1 = ("abc", "def", "ghi", "jkl", "mno", "pqr"); 
my @array2=@array1[2 .. 4];              # ====> @array1 not $array1
print join(",", @array2), "\n";
like image 146
perreal Avatar answered Aug 01 '26 01:08

perreal


The syntax for a list slice is @array[EXPR] (not $array[EXPR]), so you want

my @array2 = @array1[2..4];

Note that the above has three loops. If you wanted to avoid looping, you'd have to use

my @array2;
$array2[0] = $array1[2];
$array2[1] = $array1[3];
$array2[2] = $array1[4];

I doubt you actually wanted to avoid looping despite the request, though.

like image 22
ikegami Avatar answered Aug 01 '26 01:08

ikegami