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

I always wonder why I should write

foreach my $x (@arr) 

instead

 foreach my $x @arr 

What is the purpose of parentheses here?

+4
source share
5 answers

Answer: Larry liked the answer to this question. when Perl 5 was created.

A more serious answer: it helps eliminate the ambiguity between " @arr over @arr , putting each value in $x " ( for $x (@arr) ) and "iterating over $x and @arr , putting each value in $_ " ( for ($x, @arr) ). And, yes, I understand that the extra comma in the latest version makes ambiguity possible even without partners, but it is less obvious to the human reader, and I expect that relying only on this will lead to big mistakes.

+2
source

I can only think of one specific reason. The following code is valid:

 for ($foo) { $_++ } 

If you want to change this to

 for $foo { $_++ } 

Then you will really talk

 for $foo{$_++} 

(i.e. hash search). Perl 6 circumvented this problem by changing the way you use spaces with variables (you cannot say %foo <bar> and mean the same thing as %foo<bar> ).

+7
source

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

 s/foo/bar/ foreach @arr; 

or

 do { ... } foreach @arr; 
+2
source

Perl has two types of functions: one works in a scalar context, and the other works in a list context. "Foreach" works in the context of the list, so its context is indicated in parentheses.

for example, take an array:

 @a = (1,2,3); 

So we can write -

 foreach my $x (@a) 

OR

 foreach my $x (1,2,3) 
-1
source

David B

In this context, they should be equivalent, however, many times parentheses either change the order of operations in which something is performed, or the type of the returned variable (listing). Different functions can handle lists against arrays / hashes in different ways.

Operating procedure

In a foreach loop, it is typical to sort the listing:
foreach my $key (sort keys %hash) { ... }

This can also be written like this:
foreach my $key (sort(keys(%hash))) { ... }

Lists

On the other hand, you should look at the difference between a list, an array, and a hash. Lists are usually the base type, where the hash / arrays have additional functions / features. Some functions will work only on lists, but not on their scalar counterpart.


Addendum:

I should also add that Randal Schwartz (co-author of Camel's first book) indicated in previous citations 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 parameter can be used interchangeably only because perl parses the contents in () and then determines which construct to use.

-1
source

All Articles