Can I access a static method in a dynamically specified class in Perl?

oop, perl

Solution

Yup! The way to do it with strictures is to use `can`.

package Foo::Bar;
use strict;
use warnings;

sub baz
{
   return "Passed in '@_' and ran baz!";
}

package main;
use strict;
use warnings;

my $class = 'Foo::Bar';

if (my $method = $class->can('baz'))
{
   print "yup it can, and it ";
   print $method->();
}
else
{
   print "No it can't!";
}

`can` returns a reference to the method, undef / false. You then just have to call the method with the dereferene syntax.

It gives:

    > perl foobar.pl
    yup it can, and it Passed in '' and ran baz!

Problem

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.

Original source