Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re^2: error printing all text in text file

by Marshall (Canon)
on Jan 13, 2022 at 05:38 UTC ( [id://11140414]=note: print w/replies, xml ) Need Help??


in reply to Re: error printing all text in text file
in thread error printing all text in text file

There are multiple problems with this snippet.
  1. This code will usually abend with throw a warning of an undefined value passed to chomp!
  2. 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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11140414]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (2)
As of 2026-02-16 23:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.