Perl‎ > ‎

Loop

Looping

foreach (1 .. 10)
{
   say "$_ * $_ = ", $_ * $_;
}

my $i = 'horse';
for $i (1 .. 10)
{
   say "$i * $i = ", $i * $i;
}
is( $i, 'horse', 'Lexical variable still not overwritten in outer scope' );

C-style loop

my $i = 'pig';
for ($i = 0; $i <= 10; $i += 2)
{
   say "$i * $i = ", $i * $i;
}
isnt( $i, 'pig', '$i overwritten with a number' );

Infinite Loop

for (;;) { ... }
while (1) { ... }

While

while (my $value = shift @values)
{
   say $value;
}

Until

until ($finished_running)
{
   ...
}

do
{
   say 'What is your name?';
   my $name = <>;
   chomp $name;
   say "Hello, $name!" if $name;
} until (eof);

Opening the filehandle outside of the for loop leaves the file position unchanged between each iteration of the for loop. On
its second iteration, the while loop will have nothing to read and will not execute. To solve this problem, you may re-open the
file inside the for loop (simple to understand, but not always a good use of system resources), slurp the entire file into memory
(which may not work if the file is large), or seek the filehandle back to the beginning of the file for each iteration (an often
overlooked option):
use autodie;
open my $fh, '<', $some_file;
for my $prefix (@prefixes)
{
   while (<$fh>)
   {
      say $prefix, $_;
   }
   seek $fh, 0, 0;
}

'next' restarts the loop, 'last' ends it and redo restart the current iteration

while (<$fh>)
{
   next if /\A#/;
   last if /\A__END__/
   if ($line =~ s{\\$}{})
   {
       $line .= <$fh>;
       redo;
       ...
       }
}





Comments