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


In reply to Re^3: Make calculation with values from hash by johngg
in thread Make calculation with values from hash by GertMT

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.