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

Pis*_*tos 5 perl hash constants perl-data-structures

我想在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' ]
Run Code Online (Sandbox Code Playgroud)

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

Eth*_*her 11

您也可以使用内置完成此操作:

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};
Run Code Online (Sandbox Code Playgroud)


Mic*_*man 8

您可以使用Hash :: Util模块来锁定和解锁哈希值(键,值或两者).

package Foo;
use Hash::Util;

our %MY_CONST = (
    foo => 'bar',
    baz => {
        innerbar => 'bleh',
    }
);

Hash::Util::lock_hash_recurse(%MY_CONST);
Run Code Online (Sandbox Code Playgroud)

然后在其他一些文件中:

use Foo;
my $b = $Foo::MY_CONST{baz}{innerbar};
Run Code Online (Sandbox Code Playgroud)

  • 所以你真的不需要常数吗?Hash :: Util的东西是让人们不会改变哈希的神奇之处. (2认同)