如何在Perl中创建嵌套哈希作为常量?
-
06-07-2019 - |
题
我想在Perl中使用以下Ruby代码:
class Foo
MY_CONST = {
'foo' => 'bar',
'baz' => {
'innerbar' => 'bleh'
},
}
def some_method
a = MY_CONST[ 'foo' ]
end
end
# In some other file which uses Foo...
b = Foo::MY_CONST[ 'baz' ][ 'innerbar' ]
也就是说,我只想声明一个常量的嵌套哈希结构,以便在类和外部使用。怎么样?
解决方案
您可以使用 Hash :: Util 模块来锁定和解锁哈希值(键,值或两者)。
package Foo;
use Hash::Util;
our %MY_CONST = (
foo => 'bar',
baz => {
innerbar => 'bleh',
}
);
Hash::Util::lock_hash_recurse(%MY_CONST);
然后在其他文件中:
use Foo;
my $b = $Foo::MY_CONST{baz}{innerbar};
其他提示
您也可以使用内置完成:
package Foo;
use constant MY_CONST =>
{
'foo' => 'bar',
'baz' => {
'innerbar' => 'bleh',
},
};
sub some_method
{
# presumably $a is defined somewhere else...
# or perhaps you mean to dereference a parameter passed in?
# in that case, use ${您也可以使用内置完成:
<*>[0]} = MY_CONST->{foo} and call some_method(\$var);
$a = MY_CONST->{foo};
}
package Main; # or any other namespace that isn't Foo...
# ...
my $b = Foo->MY_CONST->{baz}{innerbar};
请参阅 Readonly :
#!/usr/bin/perl
package Foo;
use strict;
use warnings;
use Readonly;
Readonly::Hash our %h => (
a => { b => 1 }
);
package main;
use strict;
use warnings;
print $Foo::h{a}->{b}, "\n";
$h{a}->{b} = 2;
输出:
C:\Temp> t 1 Modification of a read-only value attempted at C:\Temp\t.pl line 21
这是perl中哈希的指南。 Hash of Hashes
不隶属于 StackOverflow