Further to stevieb's remarks++ about properly understanding the context in which the $fh filehandle is read in the OPed while-loop, note that if you had enabled strict at the start of your code, the code would not even have compiled due to the absence of an explicit declaration of a @line array before using it. ($line[n] accesses the @line array). So (all code examples untested)
would have failed to compile and would have thrown an error message about the undeclared @line array that might have pointed you in the right debugging direction.use strict; $filename = 'result.txt'; open( my $fh, '<', $filename ) or die "Can't open '$filename': $!"; while ( my $line = <$fh> ) { print "something here $line[0]"; print "something here $line[1]"; print "something here $line[2]"; } close $fh;
If a @line array had, for some reason, been declared before the while-loop, there would have been no compile-time error, but the use of the warnings module would have produced a run-time warning (not an error | a fatal error) about the use of an uninitialized variable:
The warning will have a source code line number associated with it which should aid in understanding the nature of the problem.use strict; use warnings; $filename = 'result.txt'; open( my $fh, '<', $filename ) or die "Can't open '$filename': $!"; my @line; while ( my $line = <$fh> ) { print "something here $line[0]"; print "something here $line[1]"; print "something here $line[2]"; } close $fh;
Bottom line: If you're a novice Perl programmer, always enable warnings and strict. If you're not a novice Perl programmer, then always enable warnings and strict — unless you have a very good and clearly understood reason not to do so.
Update: As hippo pointed out, we have Tutorials in the Monastery, and Use strict and warnings is a good one about strict (and warnings). See also the supplementary links at the end of the article.
Give a man a fish: <%-{-{-{-<
In reply to Re: Print contents of text file line by line
by AnomalousMonk
in thread Print contents of text file line by line
by TonyNY
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |