Reopening a Standard Filehandle

11.5 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 already got an open filehandle named FRED, say), 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 that one's 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 now have an idea about how you could send error messages to a file, rather than to your program's standard error stream:[19]

[19] Don't do this without a reason. It's nearly always better to let the user set up redirection when launching your program, rather than have redirection hardcoded. But this is handy in cases where your program is being run automatically by another program (say, by a web server or a scheduling utility like cron or at). Another reason might be that your program is going to start another process (probably with system or exec, which we'll see in Chapter 14), and you need that process to have different I/O connections.

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

After reopening STDERR, any error messages from Perl will go into the new file. But what happens if the or die part 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 be reopened, Perl kindly restores the original one.[20] 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,[21] almost as if the program had been run with that I/O redirection from the shell in the first place.

[20] At least, this is true if you haven't changed Perl's special $^F variable, which tells Perl that only those three are special like this. But you'd never change that.

[21] But don't open STDIN for output or the others for input. Just thinking about that makes our heads hurt.

 



Learning Perl
Learning Perl, 5th Edition
ISBN: 0596520107
EAN: 2147483647
Year: 2001
Pages: 205

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net