Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

oop

perl

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.

like image 362
chuck Avatar asked Oct 27 '09 22:10

chuck


People also ask

Can I call a static method inside a regular one?

@Ian Dunn Put simply, $this only exists if an object has been instantiated and you can only use $this->method from within an existing object. If you have no object but just call a static method and in that method you want to call another static method in the same class, you have to use self:: .

What is@ staticmethod Python?

The @staticmethod is a built-in decorator that defines a static method in the class in Python. A static method doesn't receive any reference argument whether it is called by an instance of a class or by the class itself.

Which TYPE of methods in a Python class get no implicit argument like self or cls)?

A static method does not receive an implicit first argument.

Is it possible to have static methods in Python?

Static methods in Python are extremely similar to python class level methods, the difference being that a static method is bound to a class rather than the objects for that class. This means that a static method can be called without an object for that class.


1 Answers

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!
like image 71
Robert P Avatar answered Sep 27 '22 17:09

Robert P