如何用Perl编写for循环?

时间:2015-05-22 06:21:03

标签: perl

如何在Perl中编写for循环?我试过以下无济于事:

my $i = 0;
for my $foo; do
    $i=$[i+1];
done < bar;

4 个答案:

答案 0 :(得分:5)

除了for语句修饰符之外,perl中还有两种类型的for循环。它们看起来像这样:

# c-style for loop
for ( my $i = 0; $i < 12; ++$i ) {
    ...
}

# regular for loop
for my $i (0..11) {
    ...
}

# statement modifier
... for 0..11;

答案 1 :(得分:2)

要在Perl中编写for循环,语法将如下所示:

for my $foo (@array) {
    print "$foo\n";
}

答案 2 :(得分:0)

for(my $i = 1; $i < 5; $i++) {
    something...
}

或foreach

my @names = qw(Steve Bill Connor Bradley);
foreach my $name (@names) {
    something...
}

答案 3 :(得分:-1)

Perl中for循环的语法是:

for ( init; condition; increment )
{
   statement(s);
}

示例:

for (my $i=0; $i <= 9; $i++)
{
   print "$i\n";
}