If you wish to terminate execution of a foreach loop without iterating over all 
of the elements (@files, in this case) use the “last” statement:

foreach my $file ( @files ) {
 # process file
 open( my $fh, ‘<‘, $file ) or die(…);
 while( my $line = <$fh> ) {
   # process line
 }
 close ($fh) or die( … );

 last if (some_condition);
}

If you wish to terminate the foreach loop from inside the while loop, you can 
give the foreach loop a label and use the label in the “last” statement. 
Without an explicit label, “last” will terminate the innermost loop (the while 
loop here):

ALL: foreach my $file ( @files ) {
 # process file
 open( my $fh, ‘<‘, $file ) or die(…);
 while( my $line = <$fh> ) {
   # process line
   last ALL if (some_condition);
 }
 close ($fh) or die( … );
}

However, in that case you have skipped the close statement, and the close will 
happen automatically when the file handle $fh goes out of scope, but you cannot 
do any explicit error checking on the close.


> On Jul 12, 2017, at 12:20 PM, perl kamal <kamal.p...@gmail.com> wrote:
> 
> Hello All,
> 
> I would like to read multiple files and process them.But we could read the 
> first file alone and the rest are skipped from the while loop. Please correct 
> me where am i missing the logic.Thanks. 
> 
> use strict;
> use warnings;
> my @files=qw(Alpha.txt Beta.txt Gama.txt);
> 
> foreach my $file (@files)
> {
> open (my $FH, $file) or die "could not open file\n";
> 
> while( my $line = <$FH> ){
> #[process the lines & hash construction.]
> }
> close $FH;
> }
> 
> Regards,
> Kamal.



Jim Gibson

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to