3

在以下短程序中:

 use Template;
 my $template = Template->new (INCLUDE_PATH => ".");
 $template->process ("non-existent-file")
      or die $template->error ();

为什么die不产生行号和换行符?我的输出如下所示:

 ~ 502 $ perl template.pl
 file error - non-existent-file: not found ~ 503 $ 
4

2 回答 2

10

Template正在返回类型的错误对象Template::Exception。该对象具有重载的字符串化,该字符串化在打印值时适用,但是在die查看该值时,它会看到一个引用并且不会附加行号和换行符。早先将值强制转换为字符串以解决问题:

use Template;
my $template = Template->new (INCLUDE_PATH => ".");
$template->process ("non-existent-file")
  or die '' . $template->error ();

印刷

file error - non-existent-file: not found at scratchpad.pl line 25.
于 2010-05-14T02:44:58.360 回答
0

虽然@Eric 的回答确实解决了 OPs 问题,但我建议附加一个空格而不是预先附加一个空字符串。

原因是如果模板有问题,会报错来自模板文本,而不是perl文件中的行号(这是我想要的)。请看这个简短的例子:

use Template;
my $template = Template->new();
# Clearly a division by zero bug
$template->process(\"[% 1 / 0 %]")
    or die $template->error();

这导致:

undef error - Illegal division by zero at input text line 1.

这不是很有帮助。我想要 perl 文件位置。相反,我建议:

my $template = Template->new();
$template->process(\"[% 1 / 0 %]")
    or die $template->error() . ' ';

产生:

undef error - Illegal division by zero at input text line 1.
  at test.pl line 11.

这样我也得到了 perl 文件中的行号。不过,它看起来确实有点难看。(你现在可以停止阅读,如果你喜欢......)

更正确的方法是:

use Template;
my $template = Template->new();
$template->process(\"[% 1 / 0 %]")
    or do {
        my $error = $template->error . '';
        chomp $error;
        die $error;
    };

产生这个输出:

undef error - Illegal division by zero at input text line 1. at t2.pl line 15.

但它是如此冗长,并且有一个奇怪.的地方。我实际上最终创建了:

sub templateError {
    my ($template) = @_;
    my $string = $template->error->as_string;
    chomp $string;
    $string =~ s/(line \d+)\.$/$1/;
    return $string;
}
...
use Template;
my $template = Template->new ();
$template->process (\"[% 1 / 0 %]")
    or die templateError($template);

所以我得到这个:

undef error - Illegal division by zero at input text line 1 at test.pl line 30.

以及 OP 示例中的这个:

file error - non-existent-file: not found at test.pl line 31.
于 2016-01-13T01:38:58.793 回答