Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

readline() on closed file-handle is coming when reading the file

by ulaksh (Acolyte)
on Aug 30, 2012 at 22:22 UTC ( [id://990863]=perlquestion: print w/replies, xml ) Need Help??

ulaksh has asked for the wisdom of the Perl Monks concerning the following question:

readline() on closed filehandle is coming when executing the perl script. I am trying to get the number of line in file which contain the X. I am not getting where is the issue.
#!/usr/bin/perl use strict; use warnings; my ($filename, $lines_num, $line, $c); $lines_num = 0; $filename = "input.txt"; open my $in, "<", $filename; while ($line = <$in>) { $c = substr($line, 0, 1); if (lc($c) eq "x") { $lines_num++; } } close($in); print "In " , $filename, " there are ", $lines_num, " lines that start with \"X\".\n";
my input file contains as below X XX XXX XXXX XXXXX XXXXXX XXXXXXX XXXXXXXX XXXXXXXXX XXXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX
And my output show "readline() on closed filehandle $in at filehandleoperator.pl line 12."

Replies are listed 'Best First'.
Re: readline() on closed file-handle is coming when reading the file
by philiprbrenan (Monk) on Aug 30, 2012 at 22:38 UTC

    Please add:

    or die "Cannot open file";

    after the open.

      Or, even better:

      or die "Cannot open file: $!";

      so that you can see the o/s error generated when the filehandle failed to open.

      Cheers,

      JohnGG

Re: readline() on closed file-handle is coming when reading the file
by 2teez (Vicar) on Aug 30, 2012 at 23:41 UTC

    OR,
    add use autodie qw(open close); just after use warnings; in your script.
    Your script should work fine, except you have other things in mind.
    For detailed information check autodie

    Cheers

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (4)
As of 2024-04-25 16:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found