3

So I figured out how to load a module whose $module_name is not known till runtime.

Now, I wish to access a hash key, whose value happens to be a CODEREF.

my $hash_key = 'SOME_KEY';
my $code_ref = ${$module_name::hash}{$hash_key};

Then say:

$code_ref->(@args);

The ${$module_name::hash}{$hash_key} is odd to me and I wonder if it works as intended?

Community
  • 1
  • 1
lzc
  • 919
  • 7
  • 16

2 Answers2

3

Sort of. What you wrote won't work ($module_name::hash is the scalar variable $hash in the package module_name), but this will:

my $code_ref = ${$module_name . "::hash"}{$hash_key};

This kind of construction is ... discouraged, and prohibited under use strict 'refs'. I don't know what your use case is, but another approach to consider is to implement some common methods in your dynamically loaded modules.

my $code_ref = $module_name->getCode($hash_key);
$code_ref->(@args);
mob
  • 117,087
  • 18
  • 149
  • 283
2
${ $module_name . "::hash" }{$hash_key}

or

( $module_name . "::hash" )->{$hash_key}

Of course, you'll have to use no strict qw( refs ); in the scope in which you do that.

my $hash = do { no strict qw( refs ); \%{ $module_name . "::hash" } };
$hash->{$hash_key}
ikegami
  • 367,544
  • 15
  • 269
  • 518