in reply to Re: Perl not able to read file
in thread Perl not able to read file

It is probably not needed to close the filehandle. From the close documentation:
You don't have to close FILEHANDLE if you are immediately going to do another open on it, because open closes it for you. (See open.)
Having said that, I would still explicitly close the file handle before reopening it. This looks cleaner and more understandable.

But the important point is that reopening the file for reading needs to be done after all required data has been printed to it.

An additional comment on the OP code is that there is no need to chomp the input line if the next statement adds a \n to it.

Replies are listed 'Best First'.
Re^3: Perl not able to read file
by choroba (Cardinal) on Sep 22, 2017 at 09:55 UTC
    > You don't have to close FILEHANDLE if you are immediately going to do another open on it

    Yes, but there's no open going on the same filehandle, there is another filehandle opened for the same file .

    Try commenting the indicated line:

    #!/usr/bin/perl use warnings; use strict; open my $OUT, '>', '1' or die $!; open my $IN, '<', '1' or die $!; print {$OUT} "$_\n" for 1 .. 20; close $OUT or die $!; # <- Comment me! print while <$IN>;

    It's true that I'd rather open the filehandle later before reading from it, not at the top of the script, but even in such situation you need to close the output filehandle before reading from the file.

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
      Yes, you're right ++. I was talking about reopening the same filehandle. And I overlooked that this is not what the OP's code was doing.