CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
while versus foreach and closing of files

 



regex2012
User

Dec 9, 2015, 7:39 PM

Post #1 of 4 (1958 views)
while versus foreach and closing of files Can't Post

Just a general question.
I was wondering how to emulate the do for portion of a bash script. For example, if I have a file with 10 lines and I want multiple actions done for each of the 10 lines, to start it off using the file would it be a while (<$fh1>) assuming $fh1 is the file which was opened with the 10 lines?
And I assume that I would close the file at the very end of all the actions?


BillKSmith
Veteran

Dec 9, 2015, 8:55 PM

Post #2 of 4 (1955 views)
Re: [regex2012] while versus foreach and closing of files [In reply to] Can't Post

Perl's "while loop" will certainly loop (see example below) through a file. I cannot say whether this will "emulate the do for portion of a bash script". Google cannot find documentation for that structure. Your name for it is probably not accurate.


Code
use strict; 
use warnings;
my $file_simulation = <<"EOF";
1
2
3
4
5
6
7
8
9
10
EOF

open my $fh1, '<', \$file_simulation or die "Cannot open simulation";

while (<$fh1>) {
s/\s*$//; # remove trailing whitespace, including newline
my $answer = 2 * $_;
print $answer, "\n";
}

Good Luck,
Bill


FishMonger
Veteran / Moderator

Dec 10, 2015, 7:04 AM

Post #3 of 4 (1934 views)
Re: [regex2012] while versus foreach and closing of files [In reply to] Can't Post

Perl does have a do .. while loop contruct which is probably closer to bash's do loop than the standard while loop.

Borrowing Bill's example, here's the amended version.

Code
#!/usr/bin/perl 

use strict;
use warnings;

my $file_simulation = <<"EOF";
1
2
3
4
5
6
7
8
9
10
EOF

open my $fh1, '<', \$file_simulation or die "Cannot open simulation";

$_ = 0;
do {
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.


regex2012
User

Dec 11, 2015, 6:41 AM

Post #4 of 4 (1888 views)
Re: [FishMonger] while versus foreach and closing of files [In reply to] Can't Post

Great info! Never knew this, thanks!

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives