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

I am a perl noob and I keep getting these errors in a particular script :

print() on closed filehandle LOG at /home/flexusr/bin/megaupdate_optio +ns_new.pl line 796. print() on closed filehandle LOG at /home/flexusr/bin/megaupdate_optio +ns_new.pl line 796.

The code is as below

796 # create the log string and print it 797 print LOG "$ts $msgType $msg\n"; 798 } 799 #============================================================= +=========

Replies are listed 'Best First'.
Re: print() on closed filehandle
by davido (Cardinal) on May 04, 2011 at 05:42 UTC

    I'd like to see the line where the file gets opened.

    Here's a thought. Put the following line somewhere near the top of your program (not the first line):

    use autodie;

    Return and report what happened.

    It's possible the file isn't opening correctly, and if you're not checking for success it's failing silently.

    bIlujDI' yIchegh()Qo'; yIHegh()! <---- extra credit. ;)


    Dave

Re: print() on closed filehandle
by wind (Priest) on May 04, 2011 at 04:51 UTC

    I don't want to be pedantic, but you're trying to print on a closed file handle. You've got two choices.

    • 1) Don't close LOG when you currently are, so that's it's still open when you try to print.
    • 2) Reopen LOG to the file that you want to write to before your print.

    Without seeing your code, can't suggest anymore than that.

Re: print() on closed filehandle
by ambrus (Abbot) on May 04, 2011 at 09:29 UTC

    Perhaps you open LOG in a different package from where you print LOG?

      Why would one package's LOG affect another's?

        That's the problem, it doesn't, but maybe the OP thinks that filehandle is global so it can be used directly from another package (hard to tell without some form of telepathy), and this is the error print would give in that case.

        Exactly! That is his point!

        Cheers Rolf

        Why would one package’s LOG affect another’s?
        Perhaps through typeglob aliasing ᴀᴋᴀ importing? *LOG = *OtherPack::LOG{IO}

        Mind you, there are handles that when used without package qualification do get auto-qualified into main:: rather than into the current package as one might otherwise expect. STDIN, STDOUT, and STDERR work that way, although stdin, stdout, and stderr are only in main::. I wouldn’t suggest using ARGV, ARGVOUT, or _, the stat-cache handle, since all are already used by Perl for their own purposes.

        But I don’t see why you couldn’t use an ENV filehandle, for example, as a sort of über-global. I don’t believe that one’s spoken for yet. The other one that appears available for such subterfuge is a SIG filehandle.

        But I don’t really suggest it: it would probably just get you talked about. 😒