6

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

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

4

4 回答 4

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};
于 2009-07-31T23:25:19.640 回答
8

您可以使用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};
于 2009-07-31T20:02:11.173 回答
4

请参阅只读

#!/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:\温度> t
1
在 C:\Temp\t.pl 第 21 行尝试修改只读值
于 2009-07-31T20:19:21.853 回答
1

这是 perl 中的哈希指南。哈希的哈希

于 2009-07-31T20:04:42.460 回答