Come posso creare un hash nidificato come costante in Perl?
-
06-07-2019 - |
Domanda
Voglio fare, in Perl, l'equivalente del seguente codice 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' ]
Cioè, voglio solo dichiarare una struttura di hash annidata costante da usare sia in classe che all'esterno. Come?
Soluzione
Puoi utilizzare il modulo Hash :: Util per bloccare e sbloccare un hash ( chiavi, valori o entrambi).
package Foo;
use Hash::Util;
our %MY_CONST = (
foo => 'bar',
baz => {
innerbar => 'bleh',
}
);
Hash::Util::lock_hash_recurse(%MY_CONST);
Quindi in qualche altro file:
use Foo;
my $b = $Foo::MY_CONST{baz}{innerbar};
Altri suggerimenti
Puoi anche farlo interamente con builtin:
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 ${ Puoi anche farlo interamente con builtin:
<*>[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};
Vedi Readonly :
#!/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;
Output:
C:\Temp> t 1 Modification of a read-only value attempted at C:\Temp\t.pl line 21
Ecco una guida agli hash in perl. Hash of Hash
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow