Dec 10, 2015, 7:04 AM
Post #3 of 4
Perl does have a do .. while loop contruct which is probably closer to bash's do loop than the standard while loop.
Re: [regex2012] while versus foreach and closing of files
[In reply to]
Borrowing Bill's example, here's the amended version.
my $file_simulation = <<"EOF";
open my $fh1, '<', \$file_simulation or die "Cannot open simulation";
$_ = 0;
s/\s*$//; # remove trailing whitespace, including newline
my $answer = 2 * $_;
print $answer, "\n";
} while (<$fh1>);
The difference is that a while loop evaluates its conditional before entering the block of of the loop while the do..while construct evaluates the conditional at the end of each iteration. The do..while is guaranteed to execute the body of the loop at least once but the standard while loop may not execute the body (block) at all if the first iteration evaluates to false.