in reply to Re: Make calculation with values from hash
in thread Make calculation with values from hash

Thanks very much, this is certainly of use as I've had two file recently that had irregular patterns somewhere. Just to make sure that I really do understand it:
next if m{^\s*$}; print qq{-->$_<--\n};
the $_ stands for the next line that's received from the file!? Yes, must be. Gert

Replies are listed 'Best First'.
Re^3: Make calculation with values from hash
by johngg (Canon) on Jan 02, 2007 at 20:54 UTC
    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