Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between 'for' and 'foreach' in Perl?

I see these used interchangeably. What's the difference?

like image 937
planetp Avatar asked Feb 17 '10 09:02

planetp


People also ask

What is the difference between foreach and for?

foreach is useful when iterating all of the items in a collection. for is useful when iterating overall or a subset of items. The foreach iteration variable which provides each collection item, is READ-ONLY, so we can't modify the items as they are iterated. Using the for syntax, we can modify the items as needed.

What is Perl foreach?

A foreach loop is used to iterate over a list and the variable holds the value of the elements of the list one at a time. It is majorly used when we have a set of data in a list and we want to iterate over the elements of the list instead of iterating over its range.

How do I iterate in Perl?

In each iteration, you can process each element of the list separately. This is why the for loop statement is sometimes referred to as foreach loop. In Perl, the for and foreach loop are interchangeable, therefore, you can use the foreach keyword in where you use the for keyword.


2 Answers

There is no difference. From perldoc perlsyn:

The foreach keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for brevity.

like image 75
Hans W Avatar answered Sep 20 '22 11:09

Hans W


I see these used interchangeably.

There is no difference other than that of syntax.

like image 25
Sarfraz Avatar answered Sep 20 '22 11:09

Sarfraz