我正在尝试为 perl 中的错误消息创建占位符模板。有什么建议么?

I am trying to create a template for placeholders for Error messages in perl. Any suggestions?

目前我有一个解决方案,但它可能不是最通用的代码。我知道有一种方法可以使用带有变量占位符的模板,而不是将实际的运行时参数放入错误消息中。抱歉,如果我问的不清楚。我不太了解如何使用模板。

 use constant {
    #list will contain more errors

    ERROR_SW => {
    errorCode => 727,
    message => sub{"Not able to ping switch $switch_ip in $timeout seconds"},
    fatal => 1,
    web_page => 'http://www.errorsolution.com/727',
    }
};

sub error_post {
    my ($error) = @_;
    print($error->{message}());   
}
    error_post(ERROR_SW);

我正在尝试设计它,以便我可以为 $switch_ip 和 $timeout 使用占位符,而不必将消息声明为子例程引用。 喜欢下面

 use constant {
    #list will contain more errors

    ERROR_SW => {
    errorCode => 727,
    message => "Not able to ping switch **{{switch_ip}}** in **{{timeout}}** seconds",
    fatal => 1,
    web_page => 'http://www.errorsolution.com/727',
    }
};

sub error_post {
    my ($error) = @_;
    print($error->{message});   
}
    error_post(ERROR_SW);

它们也像这样出现在代码中:

%%error%%

我不确定如何创建处理参数的模板。 再次为含糊不清或没有很好地解释这一点而道歉。

我无法立即看出这种方法能为您带来哪些 printf 格式无法提供的功能 ,但是 我建议您使用 Text::Template module to do it this way. It is less extensive than Template::Toolkit 但完全适合您的目的

这是使用 Text::Template 的程序的样子。希望对你有帮助

use strict;
use warnings 'all';

use Text::Template qw/ fill_in_string /;

use constant {
    ERROR_SW => {
        errorCode => 727,
        message   => 'Not able to ping switch {$switch_ip} in {$timeout} seconds',
        fatal    => 1,
        web_page => 'http://www.errorsolution.com/727',
    }
};

my $values = {
    switch_ip => '192.168.0.1',
    timeout   => 60,
};

sub error_post {
    my ($error) = @_;
    print( fill_in_string($error->{message}, hash => $values) );
}

error_post(ERROR_SW);

输出

Not able to ping switch 192.168.0.1 in 60 seconds

我会为您项目中的每种错误类型创建一个包。每个错误对象都应具有描述错误的必要属性和提供人类可读消息的 as_string() 方法。

可以使用普通的面向对象框架(例如 Moose)编写这些包。使用良好的旧 perl 对象,它可能看起来像这样:

package My::Error;

sub new {
    my ($class, %self) = @_;
    bless \%self, $class;
}

package My::Error::SW;
use parent 'My::Error';

sub as_string {
    my $self = shift;

    return sprintf "Not able to ping switch %s in %s seconds", $self->{switch_ip}, $self->{timeout};
}

CPAN 上存在多个框架。一个例子是使用 Moose 的 Throwable 模块。