如何在 Perl 中将文件句柄指向 STDOUT(或另一个文件句柄)? [英] How Do I Point a File Handle to STDOUT (or Another File Handle) In Perl?

查看:30
本文介绍了如何在 Perl 中将文件句柄指向 STDOUT(或另一个文件句柄)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个快速脚本,如果给定文件,则写入文件,如果没有给定文件,则写入标准输出.如果我可以通过将一个新的文件句柄 OUTFILE 指向其中的任何一个来启动脚本,那么我这样做会容易得多.

I want to make a quick script that writes to a file if a file is given, or stdout if no file is given. It would be much easier for me to do this if I could start the script by pointing a new file handle, OUTFILE, to whichever of these is appropriate.

我知道我可以通过在适当的时候将 STDOUT 指向我的输出文件来完成我想要的,但我宁愿不这样做,因为我不想让以后使用脚本的任何人感到困惑,并想知道为什么他们的打印语句不不行.此外,我仍然希望自己偶尔使用 print 语句进行故障排除,并且从不希望将此打印到输出文件中.

I know I can accomplish what I want by just pointing STDOUT to my output file when appropriate, but I'd rather not do that as I don't want to confuse anyone using the script later and wondering why their print statements don't work. Also, I'd still like to use the occasional print statement myself for troubleshooting purposes, and never want this print to the output file.

综上所述,我正在寻找的是以下内容:
open( OUTFILE, ($output ? ">$output" : STDOUT );
除非那不起作用.

All of this said, what I'm looking for is something along the lines of:
open( OUTFILE, ($output ? ">$output" : STDOUT );
except that doesn't work.

想法?

推荐答案

一些方法(globs):

Some ways (globs):

# Requires 2-arg open, unfortunately
open(OUTPUT, "> ".($output || '-'))  or die;

if ($output) {
   open(OUTPUT, '>', $output) or die;
} else {
   *OUTPUT = *STDOUT;
}

if ($output) {
   open(OUTPUT, '>', $output) or die;
} else {
   open(OUTPUT, '>&', \*STDOUT) or die;
}

某些方式(词法变量):

Some ways (lexical var):

# Requires 2-arg open, unfortunately
open(my $fh, "> ".($output || '-'))  or die;

my $fh;
if ($output) {
   open($fh, '>', $output) or die;
} else {
   $fh = \*STDOUT;
}

my $fh;
if ($output) {
   open($fh, '>', $output) or die;
} else {
   open($fh, '>&', \*STDOUT) or die;
}

某些方式(其他):

# Changes the default handle for <print "foo">.
if ($output) {
   open(OUTPUT, '>', $output) or die;
   select(OUTPUT);
}

这篇关于如何在 Perl 中将文件句柄指向 STDOUT(或另一个文件句柄)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆