【问题标题】:Why doesn't die $template->error() show a line number?为什么 die $template->error() 不显示行号?
【发布时间】:2011-02-19 08:36:08
【问题描述】:

在以下短节目中:

 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 $ 

【问题讨论】:

    标签: perl template-toolkit


    【解决方案1】:

    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.
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2014-06-18
        • 2018-02-05
        • 1970-01-01
        • 2013-08-26
        • 2018-11-10
        • 2017-02-12
        • 2016-11-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多