Is it possible to dynamically specify a class in Perl and access a static method in that class? This does not work, but illustrates what I'd like to do:
use Test::Class1;
my $class = 'Test::Class1';
$class::static_method();
I know I can do this:
$class->static_method();
and ignore the class name passed to static_method, but I wonder if there's a better way.
Yup! The way to do it with strictures is to use
can
.can
returns a reference to the method, undef / false. You then just have to call the method with the dereferene syntax.It gives:
You can use string eval:
Output:
Benchmarks:
Output:
As always with Perl, there is more than one way to do it.
You can use the special
%::
variable to access the symbol table.You could just simply use a symbolic reference;
You could also use a string
eval
.The simplest in this case, would be to use
UNIVERSAL::can
.I am unaware of a particularly nice way of doing this, but there are some less nice ways, such as this program:
I have included a
$class
variable, as that was how you asked the question, and it illustrates how the class name can be chosen at runtime, but if you know the class beforehand, you could just as easily call&{"Test::Class1::static_method"}(1, 2, 3);
Note that you have to switch off
strict "refs"
if you have it on.There are three main ways to call a static function:
$object->static_method()
Classname->static_method()
Classname::static_method()
You could define your function like this:
or like this, which works in all three calling scenarios, and doesn't incur any overhead on the caller's side like Robert P's solution does: