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