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:\Temp> t
1
C:\Temp\t.pl 行 21 で試行された読み取り専用値の変更
于 2009-07-31T20:19:21.853 に答える
1

Perl のハッシュのガイドを次に示します。ハッシュのハッシュ

于 2009-07-31T20:04:42.460 に答える