Reopening a Standard Filehandle

We mentioned earlier that if you were to reopen a filehandle (that is, if you were to open a filehandle FRED when you’ve got an open filehandle named FRED), the old one would be closed for you automatically. And we said that you shouldn’t reuse one of the six standard filehandle names unless you intended to get its special features. And we also said that the messages from die and warn, along with Perl’s internally generated complaints, go automatically to STDERR. If you put those three pieces of information together, you will have an idea about how you could send error messages to a file rather than to your program’s standard error stream:[154]

    # Send errors to my private error log
    if ( ! open STDERR, ">>/home/barney/.error_log") {
      die "Can't open error log for append: $!";
    }

After reopening STDERR, any error messages from Perl will go into the new file. What happens if the die is executed—where will that message go if the new file couldn’t be opened to accept the messages?

The answer is that if one of the three system filehandles—STDIN, STDOUT, or STDERR—fails to reopen, Perl kindly restores the original one.[155] That is, Perl closes the original one (of those three) only when it sees that opening the new connection is successful. Thus, this technique could be used to redirect any (or all) of those three system filehandles from inside your program,[156] almost as if the program had been run with that I/O redirection from the shell in the first place. ...

Get Learning Perl, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.