虽然@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.