What is the difference between for and foreach in Perl?

In the Perl programming language has keywords for and foreach. They are used to create loops.

Between them there is no difference. Everywhere is for you can always use foreach and is foreach you can always use for.

But there is a recommendation. Perl has 2 types of cycles which can be done using for or foreach. The recommendation is that for each type of cycle to always use your the key word here. For loop similar to the loop in the C language to use only for, and for the other cycles use only foreach. If you follow this simple rule then there is the question of when to use it, and reading code becomes a little easier.

Cycle as in the C language

After the C programming language this type of loop in Perl looks very familiar.

After for 3 in parentheses is the code snippet:

  • the initial value
  • check
  • change
▶ Run
#!/usr/bin/perl

for (my $i=0; $i < 3; $i++) {
    warn $i;
}

This same code will work the same way there is for use foreach. But there is a recommendation for this type cycle use only for and not use foreach.

Loop — iterate through

The second type of cycle which can be written using for or foreach in Perl is iterating through the items in the list. This type of cycle is quite similar to what is in the C programming language.

▶ Run
#!/usr/bin/perl

foreach my $el (1, 2, 3) {
    warn $el;
}

If you write for is foreach, then this loop will run exactly the same. But there is a recommendation for this type cycle use only foreach and not use for.

Postfix cycle

A variation of the preceding cycle. This option would also work the same way in the case of for and foreach, but the recommendation in this case to use only foreach.

▶ Run
#!/usr/bin/perl

warn $_ foreach (1, 2, 3);

Other articles

Comments