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".
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";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With