Perlでネストされたハッシュを定数として作成するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/1214541

質問

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

読み取り専用を参照してください:

#!/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でのハッシュのガイドです。 ハッシュハッシュ

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top