如何读取变量/值,它是一个常量哈希列表中的运行时参数?

时间:2016-03-10 13:45:29

标签: perl error-handling constants subroutine hash-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);

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

1 个答案:

答案 0 :(得分:3)

如上所述,您的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 暗示in his comment的另一种方法是将message字段的值设为子例程引用。这可以在运行时执行以合并参数的当前值。该解决方案看起来像这样

请注意$error->{message}()末尾的附加括号,以便将引用称为,而不是已评估

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