Perl Learning: 5.10. Reopening a Standard Filehandle

Previous Page
Next Page

 

5.10. 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:[*]

[*] 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
    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 executedwhere 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 filehandlesSTDIN, STDOUT, or STDERRfails to reopen, Perl kindly restores the original one.[] 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,[] almost as if the program had been run with that I/O redirection from the shell in the first place.

[] 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.

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

Previous Page
Next Page
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值