我如何读入一个 variable/value ,它是一个常量哈希列表中的运行时参数?

How can I read in a variable/value which is a runtime parameter that is inside a constant list of hashes?

我曾尝试将变量放入字符串中,但当我 运行 程序时它显示为空白。这是我正在使用的示例:

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

我只是想 post 字符串中包含变量值的错误。

如前所述,您的ERROR_SW是一个常量,可能不包含运行时间变量

如果您希望 $switch_ip$timeout 也是常量值,那么,因为 use constant 是在编译时评估的,您还必须事先声明和定义这两个变量.像这样

use strict;
use warnings 'all';

my ($switch_ip, $timeout);

BEGIN {
    ($switch_ip, $timeout) = qw/ 127.0.0.1 30 /;
}

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',
    }
};

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

error_post(ERROR_SW);



但是我认为您的意思是消息随这些变量的值而变化,这对于常量是不可能的。通常的方法是将错误消息定义为具有包含 printf 字段说明符的常量错误消息字符串。比如这样

use strict;
use warnings 'all';

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

my ( $switch_ip, $timeout ) = qw/ 127.0.0.1 30 /;

sub error_post {
    my ($error) = @_;
    printf $error->{message}, $switch_ip, $timeout;
}

error_post(ERROR_SW);

输出

Not able to ping switch 127.0.0.1 in 30 seconds



choroba 暗示 的另一种方法是使 message 字段的值成为 子例程引用。可以在 运行 时间执行以合并参数的当前值。该解决方案看起来像这样

请注意 $error->{message}() 末尾的附加括号,以调用引用 called 而不是 evaluated

use strict;
use warnings 'all';

my ($switch_ip, $timeout);

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

($switch_ip, $timeout) = qw/ 192.168.0.1 99 /;

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

error_post(ERROR_SW);

输出

Not able to ping switch 192.168.0.1 in 99 seconds