Even more readable: FILE: foreach my $file ( @files ) } ... last FILE if (some_condition); ... }
Also note that lexical filehandles close when they go out of scope, except for the most recently "stat"ed file. Perl holds a reference to "the most recently stat-ed filehandle" in "the solitary underscore" as discussed in the documentation about -X <https://perldoc.perl.org/functions/-X.html>. The upshot is that a filehandle used in an expression like "-M $fh" will live until the next such expression, and the filehandle used in the last such expression won't close until the end of the program. David On Wed, Jul 12, 2017 at 5:28 PM, Jim Gibson <jimsgib...@gmail.com> wrote: > 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/ > > > -- "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." -- Brian Kernighan