gpt4 book ai didi

perl - 如何在 Perl 中创建嵌套哈希作为常量?

转载 作者:行者123 更新时间:2023-12-04 16:21:54 24 4
gpt4 key购买 nike

我想在 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' ]

也就是说,我只想声明一个常量、嵌套的哈希结构,以便在类中和外部使用。如何?

最佳答案

您也可以完全使用内置函数执行此操作:

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};

关于perl - 如何在 Perl 中创建嵌套哈希作为常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1214541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com