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?
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?
BTW, you can use the expression form of the for
without parentheses like this:
s/foo/bar/ foreach @arr;
or
do { ... } foreach @arr;
Flippant answer: Because that's the way Larry likes it liked it when Perl 5 was created.
More serious answer: It helps to disambiguate between "iterate over @arr
, putting each value into $x
" (for $x (@arr)
) and "iterate over $x
and @arr
, putting each value into $_
" (for ($x, @arr)
). And, yes, I realize that the extra comma in the latter version does make disambiguation possible even without the parens, but it's less obvious to a human reader and I expect that relying on that alone would lead to more errors.
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>
).
Perl has two types of functions - one works in scalar context and another works in list context.'Foreach' works in list context so parentheses indicate the its context.
like assume a array:
@a = (1,2,3);
So we can write -
foreach my $x (@a)
OR
foreach my $x (1,2,3)
David B,
In this context they should be equivalent, however many times parentheses either change the order of operation in which something is performed, or the type of variable returned (a listing). Different functions may handle lists vs arrays/hashes differently.
During a foreach loop, it's typical to sort a listing:
foreach my $key (sort keys %hash) { ... }
This could also be written as:
foreach my $key (sort(keys(%hash))) { ... }
On the other hand, you should look at the difference between a list, array, and hash. Lists are generally the base type, where hash/arrays have additional functions/abilities. Certain functions will only operate on lists, but not their scalar counterpart.
I think I should also add, as Randal Schwartz (co-author of the first Camel book) has pointed out in previous citings, that the "for" loop is from C and the "foreach" loop is from Csh. What is inside the parentheses is used to determine which loop is used by perl. The for/foreach can be used interchangeably only because perl examines the contents in the ()
and then determines which construct to use.