问题
I see these used interchangeably. What's the difference?
回答1:
There is no difference. From perldoc perlsyn:
The
foreach
keyword is actually a synonym for thefor
keyword, so you can useforeach
for readability orfor
for brevity.
回答2:
I see these used interchangeably.
There is no difference other than that of syntax.
回答3:
Four letters.
They're functionally identical, just spelled differently.
回答4:
Ever since its introduction in perl-2.0, foreach
has been synonymous with for
. It's a nod to the C shell's foreach command.
In my own code, in the rare case that I'm using a C-style for-loop, I write
for (my $i = 0; $i < $n; ++$i)
but for iterating over an array, I spell out
foreach my $x (@a)
I find that it reads better in my head that way.
回答5:
From http://perldoc.perl.org/perlsyn.html#Foreach-Loops
The foreach keyword is actually a synonym for the for keyword, so you can use either. If VAR is omitted, $_ is set to each value.
# Perl's C-style
for (;;) {
# do something
}
for my $j (@array) {
print $j;
}
foreach my $j (@array) {
print $j;
}
However:
If any part of LIST is an array, foreach will get very confused if you add or remove elements within the loop body, for example with splice. So don't do that.
回答6:
The foreach keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for brevity. (Or because the Bourne shell is more familiar to you than csh, so writing for comes more naturally.) If VAR is omitted, $_ is set to each value.
回答7:
There is a subtle difference (http://perldoc.perl.org/perlsyn.html#Foreach-Loops) :
The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn. If the variable is preceded with the keyword my, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with my, it uses that variable instead of the global one, but it's still localized to the loop. This implicit localization occurs only in a foreach loop.
This program :
#!/usr/bin/perl -w
use strict;
my $var = 1;
for ($var=10;$var<=10;$var++) {
print $var."\n"; # print 10
foo(); # print 10
}
print $var."\n"; # print 11
foreach $var(100) {
print $var."\n"; # print 100
foo(); # print 11 !
}
sub foo {
print $var."\n";
}
will produce that :
10
10
11
100
11
回答8:
In case of the "for" you can use the three steps.
1) Initialization 2) Condition Checking 3) Increment or decrement
But in case of "foreach" you are not able increment or decrement the value. It always take the increment value as 1.
来源:https://stackoverflow.com/questions/2279471/whats-the-difference-between-for-and-foreach-in-perl