首页 > 解决方案 > 如何将一行中的哈希引用转换为perl中的常量

问题描述

我正在使用Sphinx::Search.

此代码示例是否有更简单的方法将字符串转换为常量?

use Sphinx::Search;

my $config = {
    x => 'SPH_MATCH_EXTENDED2',
};

my $x = $config->{x};
print Sphinx::Search->$x(); # output: 6

我使用了 如何在 Perl 中访问名称包含在变量中的常量的建议? 这个例子有效,但如果我总是使用哈希中的字符串,那么我是否需要将它放入一个单独的变量中才能以这种方式使用它?

my $x = $config->{x};
print Sphinx::Search->$x(); # output: 6

有没有一种方法可以解决这个问题?

# does not work
print Sphinx::Search->$config->{x}();

标签: stringperlcastingconstants

解决方案


您可以创建对该值的引用并立即取消引用它:

Sphinx::Search->${ \$config->{x} };

(如果没有参数,则()是可选的)。


推荐阅读