There are multiple problems with this snippet.
- This code will usually
abend with throw a warning of an undefined value passed to chomp!
- The last line of the file can be missed if its not terminated by \n.
What
while (chomp (my $line = <$fh>)){} means is execute the while code if chomp is successful in removing at least 1 character from $line.
Assuming that the last line is terminated properly, after all data is read from the filehandle, $line will be undefined. chomp won't like that and will barf.
Now if the last line of the file is not terminated, an even more insidious thing can happen. That last line will be ignored because chomp does not remove any characters from that line.
So, don't use this construct.
here is proof:
use strict;
use warnings;
$|=1;
my $data = <<END;
asdf fjfjf
324
0
2345
2wefrwef
END
#chomp $data; #toggle on/off to see results
open my $fh, "<", \$data or die "$!";
while (chomp (my $line = <$fh>))
{
print $line;
}
__END__
asdf fjfjf324023452wefrwefUse of uninitialized value $line in chomp at
+ testchompWhile.pl line 15, <$fh> line 5.
asdf fjfjf32402345
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.