如何将字符串变量中的值插入perl中的常数?
我在perl中编写一个函数,其中将字符串作为参数传递,我需要将字符串解释为引用值。字符串看起来像这样: “ Edible => 1; fruit => Strawberry;”
现在,可变零件将使用哈希存储,但是,该值已经使用常数定义。我的问题是,一旦我将值存储到临时变量中,如何将其转换为常数的值? 这是一些示例代码:
#!/usr/bin/perl
require Exporter;
our @ISA = 'Exporter';
our @EXPORT = qw(STRAWBERRY TANGERINE PEAR APPLE PERSIMMON FUNC_Interpreter);
use constant {
STRAWBERRY => 1
,TANGERINE => 2
,PEAR => 3
,APPLE => 4
,PERSIMMON => 5
};
sub FUNC_Interpreter {
my ($analyze_this) = @_;
my @values;
foreach my $str (split (/;/, $analyze_this)) {
my ($key, $value) = split /=>/, $str;
push (@values, @{[ $value ]}); # Problem line! I want to store the numeric value here. This doesn't work... :(
}
}
FUNC_Interpreter ("HELLO=>TANGERINE;HELLO=>STRAWBERRY");
因此,基本上,我想做的是将一个字符串转换为一个存储在变量中的常数的名称,即变为常数的值。这可能吗?
I am writing a function in Perl, where a string is passed as an argument, and I need to interpret the string into the referenced value. The string would look something like this:"Edible => 1;Fruit => STRAWBERRY;"
Now, the variable part will be stored using hashes, however, the value is already defined using constants. My question is, once I store the value into a temporary variable, how do I convert it into the value of the constant?
Here is some example code:
#!/usr/bin/perl
require Exporter;
our @ISA = 'Exporter';
our @EXPORT = qw(STRAWBERRY TANGERINE PEAR APPLE PERSIMMON FUNC_Interpreter);
use constant {
STRAWBERRY => 1
,TANGERINE => 2
,PEAR => 3
,APPLE => 4
,PERSIMMON => 5
};
sub FUNC_Interpreter {
my ($analyze_this) = @_;
my @values;
foreach my $str (split (/;/, $analyze_this)) {
my ($key, $value) = split /=>/, $str;
push (@values, @{[ $value ]}); # Problem line! I want to store the numeric value here. This doesn't work... :(
}
}
FUNC_Interpreter ("HELLO=>TANGERINE;HELLO=>STRAWBERRY");
So basically, what I want to do is convert a string, which is actually the name of a constant stored in a variable, into a constant's value. Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

常数可以视为潜艇。
或者,
但这是一种猛烈的冒险方法。第二版甚至隐藏了您危险地允许用户在任何软件包中调用任何子。我要做的是:
使用这种方法,可以对输入进行琐碎的验证,而无效的输入仅导致Undef。
Constants can be treated as subs.
or
But that's a hackish risky approach. And the second version even hides that you are dangerously allowing the user to call any sub in any package. What I would do instead:
Using this approach, inputs can be validated trivially, and invalid inputs merely result in undef.