http://qs321.pair.com?node_id=569172

aplonis has asked for the wisdom of the Perl Monks concerning the following question:

I have need of calling any one of umpteen methods, like so...

print join ', ', Module::Submodule::Method( @args );

...where the arg list varies by quantity, etc. The real call is for Device::LabJack with a sample method call like so...

Device::LabJack::AISample( @args );

...and where the method might be 'AISample', 'EAnalogIn', 'EAnalogOut', or any of a long list of others. I don't want to write a separate call for each. What I'd very much like is some means of passing that method name in as a variable...the same variable which I now employ to trigger assembly of an appropriate arg list. Some way of doing what would otherwise look like the (incorrect) usage below...

Device::LabJack::$some_var_name( @args );

Might there be some methodology whereby I can pass a variable to stand in for the method name? I could then use a single outer method to pass that name to the inner like so...

sub pass_thru { my $self = shift; my $method_name = shift; my @args = ...assemble args for $method_name... return Device::Labjack::$_[0](@args)

Thanks,

Gan Uesli Starling

Replies are listed 'Best First'.
Re: Using $variable in place of "Method" in Module::Submodule::Method( @args )
by Joost (Canon) on Aug 23, 2006 at 19:25 UTC
    PackageName::subname() is not how you call a method. That's how you call a normal subroutine in package PackageName.

    Anyway...

    # call a method by name. # this works for real methods only. my $method = "some_method"; ClassName->$method(@arguments); $object->$method(@arguments); # or .... # get a subroutine reference and call that # this works provided you call it the right way my $subref = Package->can("some_method"); # call subref as class method Package->$subref(@args); # call subref as object method $object->$subref(@args); # call subref as normal subroutine $subref->(@args);

    The last construct is probably what you need.

Re: Using $variable in place of "Method" in Module::Submodule::Method( @args )
by izut (Chaplain) on Aug 23, 2006 at 19:25 UTC

    Here is an example:

    #!/usr/bin/perl use strict; use warnings; package Module::MyModule; sub pass { my ($function, @args) = @_; my $f = \&{"Module::MyModule::" . $function}; return $f->(@args); } sub test { my (@args) = @_; return join ", ", @args; } package main; print Module::MyModule::pass("test", qw(1 2 3 4));

    Update: modified to support strict.

    Igor 'izut' Sutton
    your code, your rules.

Re: Using $variable in place of "Method" in Module::Submodule::Method( @args )
by broquaint (Abbot) on Aug 24, 2006 at 14:53 UTC
    Seems like a good place to use can e.g
    use Carp 'croak'; sub pass_thru { my($self, $method, @args) = @_; my $func = $self->can($method); croak "No such function '$method' in ".(ref $self || $self) unless $func; return $func->(@args); }
    HTH

    _________
    broquaint