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