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)
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;
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.
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:
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;
The warning will have a source code line number associated with it which should aid in understanding the nature of the problem.
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: <%-{-{-{-<
|