Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing $ on loop variable

Tags:

arrays

perl

#!/usr/bin/perl
use strict;
use warnings;

my @array = qw[a b c];
foreach my($a,$b,$c) (@array) {
    print "$a , $b , $c\n";
}

I receive following error:

Missing $ on loop variable

What is wrong?

I am using: perl v5.10.1 (*) built for x86_64-linux-thread-multi

like image 530
name Avatar asked Nov 28 '22 12:11

name


2 Answers

To grab multiple list items per iteration, use something like List::MoreUtils::natatime or use splice:

my @tmparray = @array; # don't trash original array
while ( my ($a,$b,$c) = splice(@tmparray,0,3) ) {
    print "$a , $b , $c\n";
}

Or reorganize your data into multiple arrays and use one of the Algorithm::Loops::MapCar* functions to loop over multiple arrays at once.

like image 99
ysth Avatar answered Dec 28 '22 01:12

ysth


I'm not aware that foreach can eat up more than one parameter at a time in Perl. I might be reading the documentation wrong.

like image 25
ivans Avatar answered Dec 28 '22 03:12

ivans