Perl中的输出流:STDERR,STDOUT,

时间:2014-04-18 17:26:12

标签: perl unix io

我知道输出流STDOUT和STDERR。无论何时打印到STDOUT,在unix shell中都可以像这样重定向输出......

deviolog@home:~$ perl test_script.pl > output.txt

deviolog@home:~$ perl test_script.pl 1> output.txt

当您打印到STDERR时,它看起来相同,但您切换到"频道" (?)2号:

deviolog@home:~$ perl test_script.pl 2> output.txt

我可以在output.txt中找到我当时正在打印的错误输出。

我的问题是,我可以访问"频道"不知怎的?3号? 有没有... ...

 print STDX "Hello World!\n";

...允许重定向,如下所示?

deviolog@home:~$ perl test_script.pl 3> output.txt

P.S。一个子问题将是关于那些"频道" ^ _ ^

3 个答案:

答案 0 :(得分:7)

您可以使用open为打开的文件描述符(fd)创建Perl文件句柄,将&=附加到模式并使用文件描述符作为文件名。在您的情况下,您使用以下内容:

open(my $fh, '>&=', 3)

例如,

$ perl -E'
   open(my $fh, ">&=", 3) or die $!;
   say fileno($fh);
   say $fh "meow";
' 3>output.txt
3

$ cat output.txt
meow

答案 1 :(得分:1)

> file2> file被称为I/O redirection2等数字为file descriptors

在Perl中,STDIN是标准输入,分别对应于文件描述符1,STDOUTSTDOUT,分别对应于文件描述符2和3。其他文件描述符没有STDX。但是您可以使用以下方法打开与其他文件描述符对应的文件句柄(请参阅open):

open my $fh, ">&", 3; # $fh will correspond to fd 3, for write

open my $fh, ">&=", 3; # $fh will correspond to fd 3, for write

在运行perl程序之前,你需要打开文件描述符3(用于写入):

perl script.pl 3> file

之后,print $fh ...等语句生成的输出将显示在file中。

答案 2 :(得分:0)

不,因为我所知道的操作系统没有为控制台程序提供第三个默认句柄。 * nix和Windows都提供stdin,stdout和stderr(0,1,2)。这些会自动提供给程序,以允许它从控制台接收输入并将正常缓冲或异常无缓冲(错误)输出写入控制台。

因此,如其他答案所示,您可以调用open()打开句柄并将其强制为fd 3,但为什么要这么麻烦?它是非标准的,有点无意义,人们会对你感到好奇。

只需使用open()打开您要写入的文件。