如何在X行Y"中打印"宽字符时立即退出Perl程序消息出现?

时间:2014-06-23 05:47:24

标签: perl unicode

我有一个Perl程序,它给了我以下输出:

Wide character in print at foo.pl line 139, <FILE> line 1.
Wide character in print at foo.pl line 139, <FILE> line 2.
Wide character in print at foo.pl line 139, <FILE> line 3.

由于我不想添加:utf8图层,我也不想关闭警告,我正在寻找一种方法来终止程序并退出并显示错误代码出现如上所示的消息。

由于print语句是抛出错误的语句,我尝试在or die语句旁边使用print,但这没有帮助。例如&GT;

print OUTPUT $_."\n" or die "Something wrong happened - $!";

我猜这不起作用,因为print并没有真正失败 - 它只是显示一条消息。

3 个答案:

答案 0 :(得分:6)

您正在寻找的是:

use warnings FATAL => 'utf8';

这将导致任何“宽字符”警告致命,并导致Perl进程死亡。

例如:

#!/usr/bin/env perl

use strict;
use warnings;
use utf8;
use feature 'say';

for (1 .. 3) {
    say "παν γράμμα";
}

say "=" x 80;

use warnings FATAL => 'utf8';

for (1 .. 3) {
    say "παν γράμμα";
}

输出:

alex@kyon:~$ ./fatal_wide.pl
Wide character in say at ./fatal_wide.pl line 9.
παν γράμμα
Wide character in say at ./fatal_wide.pl line 9.
παν γράμμα
Wide character in say at ./fatal_wide.pl line 9.
παν γράμμα
================================================================================
Wide character in say at ./fatal_wide.pl line 17.

退出时退出状态为非零:

alex@kyon:~$ echo $?
255

答案 1 :(得分:2)

您需要捕获类似的Perl警告:

local $SIG{__WARN__} = sub {
    my $mes = shift;
    die $mes;
};

答案 2 :(得分:2)

如果邮件匹配,您可以提供自定义warn处理程序,然后die

#!/usr/bin/perl

use strict;
use warnings;
use utf8;

local $SIG{__WARN__} = sub {
    my $msg = shift;
    die $msg if (index $msg, "Wide character in print") > -1;
    warn $msg;
};

warn "test warn";
print "鸡\n";
warn "won't reach";

产地:

test warn at foo.pl line 17.
Wide character in print at foo.pl line 18.