Perl:关于标准输出STDOUT和标准错误STDERR


开始了 Perl语言编程 的学习。

Perl中有一些预定义的文件句柄。如标准输入STDIN、标准输出STDOUT、和标准错误STDERR。标准错误STDERR是一个额外的输出路径。怎样理解这句话呢?先来看个例子。

% perl -e 'print "Hello, World!\nabc"; print STDERR "Hi\n";'

输出:

Hello, World!
Hi
abc

而不是:

Hello, World!
abc
Hi

这是因为perl print函数是行缓冲。当碰到\n,print就立即把“标准输出”打印出来。而后面的abc因为没有碰到换行,所以先存在缓冲区,等到缓冲区满了再打印。错误输出是没有缓冲的,所以就立即打印出来了。

% perl -e 'print "Hello, World!\nabc"; print STDERR "Hi\n";' >err.txt

输出到err.txt:

Hello, World!
abc

而err.txt中没有包含Hi(Hi 仍然输出到屏幕),这只不过是把标准输出导入到了文件。如果要导入标准错误你必须这样:  

% perl   -e 'print "Hello, World!\nabc"; print STDERR "Hi\n";'   >&err.txt

>& 只用在unix和linux下的标准错误重定向。windows下是   2>

一般而言,print 只是等同于 print STDOUT 标准输出。当在输出到文件时,我们就可以通过用标准错误STDERR把错误输出的屏幕上。这样子,perl一边在工作(STDOUT 标准输出到文件时),也能即时看到错误(标准错误STDERR)。(注:以前我一直想这样实现,今天才明白过来。)

如:

% perl -e 'print STDOUT "Hello, World!\n"; print STDERR "Error\n";' >err.txt

《“Perl:关于标准输出STDOUT和标准错误STDERR”》 有 1 条评论

  1. C++手册里有这句话:
    Although generally both stdout and stderr are associated with the same console output, applications may differentiate between what is sent to stdout and what to stderr for the case that one of them is redirected. For example, it is frequent to redirect the regular output of a console program (stdout) to a file while expecting the error messages to keep appearing in the console screen.

    可以解释在屏幕同时看到err message的现象。。。

    % perl -e ‘print STDOUT “Hello, World!\n”; print STDERR “Error\n”;’ >err.txt