如何在Perl中访问名称包含在变量中的常量? [英] How do I access a constant in Perl whose name is contained in a variable?
问题描述
我在Perl中声明了一组常量:
I have a set of constants declared in Perl:
use constant C1 => 111;
use constant C2 => 222;
..
use constant C9 => 999;
my $which_constant = "C2";
我如何构造一个基于$which_constant
的Perl表达式,该表达式派生以该变量的值命名的常量的值-例如"222".
How do I construct a Perl expression which, based on $which_constant
, derives the value of a constant named with the value of this variable - e.g. "222".
请注意,我不能更改上述任何条件-它们是实际情况的简化:我有一个模块(我无法控制),可以从中导入这些常量.常量之一的名称由用户从命令行提供.我需要访问适当的常量的值.
Please note that I can not change any of the conditions above - they are a simplification of a real scenario: I have a module (which I have no control over) from which these constants are imported. The `name of one of the constants is supplied by the user from command line. I need to access the appropriate constants' value.
我一直在撞墙(主要是在各种各样的怪异的glob构造周围),但没有一个起作用.
I've been beating my head against the wall (mostly around all sorts of weird glob constructs) but none of them work.
P.S.如果解决方案访问其本机模块中的常量-说My::Constants::C2
(无需导入),则更好,但不是必须的-我可以使用My::Constants->import($which_constant)
轻松地将正确的常量导入到main::
中.是的,最重要的是,默认情况下不会导出te常量,因此需要显式import()调用.
P.S. If the solution accesses the constants inside their native module - say My::Constants::C2
(without needing to import them), even better, but not necessary - I can import the correct constants into main::
easily using My::Constants->import($which_constant)
. and yes, to top it off, te constants are NOT exported by default thus needing the explicit import() call.
我尝试过的一些事情:
-
main::$which_constant
-语法错误
main::${which_constant}
-语法错误
${*$which_constant}
-返回空值
*$which_constant
-返回"* main :: C2"
*$which_constant
- returns "*main::C2"
${*${*which_constant}}
-空
推荐答案
由 constant.pm
定义的常量只是子例程.如果字符串中包含常量的名称,则可以使用方法调用语法:
Constants defined by constant.pm
are just subroutines. You can use method invocation syntax if you have the name of the constant in a string:
#!/usr/bin/perl -l
use strict; use warnings;
use constant C1 => 111;
use constant C2 => 222;
print __PACKAGE__->$_ for qw( C1 C2 );
# or print main->$_ for qw( C1 C2 );
这样,如果您尝试使用未定义的常量,则会收到错误消息.
This way, if you try to use a constant which is not defined, you will get an error.
这篇关于如何在Perl中访问名称包含在变量中的常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!