Yes, you have that correctly. Put simply, if you read from a filehandle in a while loop without explicitly assigning what's read to a different variable, it goes into $_, i.e. while (<$inFH>) { # $_ gets each line in here } whereas while (my $line = <$inFH>) { # $line gets each line in here }.
I think that only holds in a while loop though. If you are reading a single line outside of a loop you have to assign to a variable. If I do the following, thinking to print just the first line of the data file
use strict;
use warnings;
my $inFile = q{spw592594.dat};
open my $inFH, q{<}, $inFile
or die qq{open: $inFile: $!\n};
<$inFH>;
chomp;
print qq{-->$_<--\n};
close $inFH
or die qq{close: $inFile: $!\n};
I get
Use of uninitialized value in scalar chomp at ./spw592594B line 11, <$
+inFH> line 1.
Use of uninitialized value in concatenation (.) or string at ./spw5925
+94B line 12, <$inFH> line 1.
--><--
because the line is read then silently thrown away because I have not assigned it to any variable. I have to assign to $_ or some other variable to be able to use it, like this
use strict;
use warnings;
my $inFile = q{spw592594.dat};
open my $inFH, q{<}, $inFile
or die qq{open: $inFile: $!\n};
$_ = <$inFH>;
chomp;
print qq{-->$_<--\n};
close $inFH
or die qq{close: $inFile: $!\n};
which produces
-->1st line<--
I hope this makes it clear what is happening.
Cheers, JohnGG |