Wie kann ich eine verschachtelte Hash als Konstante in Perl erstellen?
-
06-07-2019 - |
Frage
ich tun möchte, in Perl, das Äquivalent des folgenden Ruby-Code:
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' ]
Das heißt, ich möchte nur eine Konstante, verschachtelte Hash-Struktur für die Verwendung erklären, sowohl in der Klasse als auch außerhalb. Wie geht das?
Lösung
können Sie den Hash rel="noreferrer"> Modul zu sperren und entsperren einen Hash ( Schlüssel, Werte oder beide).
package Foo;
use Hash::Util;
our %MY_CONST = (
foo => 'bar',
baz => {
innerbar => 'bleh',
}
);
Hash::Util::lock_hash_recurse(%MY_CONST);
Dann in einer anderen Datei:
use Foo;
my $b = $Foo::MY_CONST{baz}{innerbar};
Andere Tipps
Sie können dies auch ganz mit builtins:
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};
Siehe Read-only :
#!/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;
Ausgabe:
C:\Temp> t 1 Modification of a read-only value attempted at C:\Temp\t.pl line 21
Hier ist ein Führer zu Hashes in Perl. Hash von Hashes
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow