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の答えはOPの問題を解決しますが、空の文字列を前に保留するのではなく、スペースを追加することをお勧めします。

その理由は、テンプレートに問題がある場合、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 に答える