+ -
当前位置:首页 → 问答吧 → Perl的错误指示变量:$@, $!, $^E, and $?

Perl的错误指示变量:$@, $!, $^E, and $?

时间:2010-11-27

来源:互联网

Perl的错误指示变量有多个,因此很容易让初学者感到迷惑。刚好在perlvar的文档里看到了详细地解释,因此摘录如下。

简单的说:

The variables $@, $!, $^E, and $? correspond to errors detected by the Perl interpreter, C library, operating system, or an external program, respectively.

详细地点说:

The variables $@, $!, $^E, and $? contain information about different types of error conditions that may appear during execution of a Perl program. The variables are shown ordered by the "distance" between the subsystem which reported the error and the Perl process. They correspond to errors detected by the Perl interpreter, C library, operating system, or an external program, respectively.

To illustrate the differences between these variables, consider the following Perl expression, which uses a single-quoted string:

eval q{
        open my $pipe, "/cdrom/install |" or die $!;
        my @res = <$pipe>;
        close $pipe or die "bad pipe: $?, $!";
    };

After execution of this statement all 4 variables may have been set.

$@ is set if the string to be eval-ed did not compile (this may happen if open or close were imported with bad prototypes), or if Perl code executed during evaluation die()d . In these cases the value of $@ is the compile error, or the argument to die (which will interpolate $! and $?). (See also Fatal, though.)

When the eval() expression above is executed, open(), <PIPE>, and close are translated to calls in the C run-time library and thence to the operating system kernel. $! is set to the C library's errno if one of these calls fails.

Under a few operating systems, $^E may contain a more verbose error indicator, such as in this case, "CDROM tray not closed." Systems that do not support extended error messages leave $^E the same as $!.

Finally, $? may be set to non-0 value if the external program /cdrom/install fails. The upper eight bits reflect specific error conditions encountered by the program (the program's exit() value). The lower eight bits reflect mode of failure, like signal death and core dump information See wait(2) for details. In contrast to $! and $^E, which are set only if error condition is detected, the variable $? is set on each wait or pipe close, overwriting the old value. This is more like $@, which on every eval() is always set on failure and cleared on success.

For more details, see the individual descriptions at $@, $!, $^E, and $?.

作者: 我不是鱼   发布时间: 2010-11-27