Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the parentheses in Perl's `foreach` statement?

I always wonder why I must write

foreach my $x (@arr)

instead of

foreach my $x @arr

What is the purpose of the parentheses here?

like image 461
David B Avatar asked Sep 06 '10 08:09

David B


2 Answers

I can only think of one concrete reason for it. The following code is valid:

for ($foo) {
    $_++
}

If you were to change that to

for $foo {
    $_++
}

Then you would really be saying

for $foo{$_++}

(i.e. a hash lookup). Perl 6 gets around this issue by changing the way whitespace works with variables (you can't say %foo <bar> and have it mean the same thing as %foo<bar>).

like image 102
Chas. Owens Avatar answered Nov 15 '22 05:11

Chas. Owens


BTW, you can use the expression form of the for without parentheses like this:

s/foo/bar/ foreach @arr; 

or

do { ... } foreach @arr;
like image 36
Eugene Yarmash Avatar answered Nov 15 '22 06:11

Eugene Yarmash