开发者

Why doesn't die $template->error() show a line number?

In the following short p开发者_StackOverflow中文版rogram:

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

why doesn't die produce a line number and newline? My output looks like this:

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


Template is returning an error object of type Template::Exception. The object has overloaded stringification which applies when the value is printed, but when die looks at the value, it sees a reference and doesn't append the line number and newline. Force the value into a string earlier to fix the problem:

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

prints

file error - non-existent-file: not found at scratchpad.pl line 25.


While @Eric's answer does solve the OPs issue, I suggest appending a space instead of pre-pending an empty string.

The reason is that if there are problems in the template, the error will be reported as coming from the template text instead of the line number in the perl file (which is what I want). See this short example:

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

This results in:

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

Which isn't very helpful. I want the perl file location. Instead I suggest:

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

which produces:

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

This way I get the line number in the perl file too. It does look a little ugly, though. (You can stop reading now, if you like...)

An even more correct way would be:

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

which produces this output:

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

But it is just so verbose and has a weird . in there. I've actually ended up creating:

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);

So that I get this:

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

as well as this for the OPs example:

file error - non-existent-file: not found at test.pl line 31.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜