我已经通过 perldoc 和 O'Reilly 书籍进行了一些挖掘,但还没有找到任何方法来做到这一点。我是否只能使用类似 Readonly 的东西? ?
更新:
我不反对 Readonly。我只是想能够做一些类似于 PHP 的常量 () 的事情。
如果 Perl 有 constant() 的例子:
use constant {
FIELD_EXAMPLE_O => 345,
FIELD_EXAMPLE_L => 25
};
my $var = 'EXAMPLE';
my $c = 'FIELD_' . $var . '_L';
my $value = constant($c);
# $value is 25
如果 Readonly 是最好的方式,那么我将使用它。
最佳答案
Readonly
有什么问题? ?
如果太慢,可以补充Readonly:XS
.但是如果你不喜欢 Readonly
, 总是有旧的 constant
.
use constant PI => 3.14159265;
记住
- 它们像潜艇一样工作,所以它们不会在没有工作的情况下进行插值。
如果您想在一条语句中创建多个常量,您需要传递一个散列引用。
use constant { PI => 3.14159265 , E => 2.71828183 };
从你的例子:
从您的示例来看,只读哈希 没有理由不能做同样的事情。
Readonly::Hash my %field_example => { L => 25, O => 345 };
然后你可以在任何你想拼凑常量的地方使用它:
print "The example is $field_example{$var}\n";
或者你可以这样做:
Readonly::Hash my %field
=> { example => { L => 25, O => 345 }
, name => { L => 'Lion', O => 'ocelot' }
};
这样调用它:
$field{$var}{L};
如果不尝试让一种语言做它更支持以另一种方式做的事情,你可以获得很多里程。
同源到 PHP 常量
但是,如果你想那样做,那么我的建议是下面的 sub 是做同样事情的一种方式(并且避免 eval
):
sub read_constant {
use Symbol qw<qualify_to_ref>;
my $name = join( '', @_ ); # no need to concatenate before passing
my $constant;
# use the first that works: calling package and then "" (main)
for my $pkg ( scalar( caller ), "" ) {
# get symbol reference
my $symb_ref = qualify_to_ref( $name, $pkg );
# get the code slot
$constant = *{$symb_ref}{CODE};
last if $constant;
}
return unless $constant;
# call the sub named
return $constant->();
}
你可以这样调用它:
$value = read_constant( 'FIELD_', $var, 'L' );
最后一件事,您甚至可以在前面进行测试以确保它只是一个全大写字符串:
Carp::croak "Invalid constant name '$name'" if $name =~ /[^\p{UpperCase}_]/;
关于php - Perl 有类似于 PHP 的 constant() 的东西吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1526859/