Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: dynamic perl calls

by osunderdog (Deacon)
on Feb 10, 2009 at 13:39 UTC ( [id://742764]=note: print w/replies, xml ) Need Help??


in reply to dynamic perl calls

It sounds like you want to do polymorphism. This is a quick example that sounds like a starting point for you.

child1.pm

package child1; sub polyexample { my $class = shift; my $param1 = shift; my $param2 = shift; print "polyexample (child1) called with [$param1] and [$param2]\n" +; } 1;

child2.pm

package child2; sub polyexample { my $class = shift; my $param1 = shift; my $param2 = shift; print "polyexample (child2) called with [$param1] and [$param2]\n" +; } 1;

main.pl

use strict; use Carp; my $class = shift; my $method = shift; my $param1 = shift; my $param2 = shift; eval("use $class"); if($@) { croak("Couldn't find package $class ($@) "); } eval($class->$method($param1, $param2)); if($@) { croak ("couldn't invoke method #method on $class with params ($@)" +) }

Finally, here are the two example invocations:

~/src/perl/poly$ perl main.pl child1 polyexample 1 2 polyexample (child1) called with [1] and [2]
~/src/perl/poly$ perl main.pl child2 polyexample 1 2 polyexample (child2) called with [1] and [2]

and an example failure

~/src/perl/poly$ perl main.pl child5 polyexample 1 2 Couldn't find package child5 (Can't locate child5.pm in @INC (@INC con +tains: /etc/perl /usr/local/lib/perl/5.10.0 /usr/local/share/perl/5.1 +0.0 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.10 /usr/share/per +l/5.10 /usr/local/lib/site_perl .) at (eval 1) line 2. BEGIN failed--compilation aborted at (eval 1) line 2.

And many wonderful permutations of this exist.

Still searching; Still seeking.

Replies are listed 'Best First'.
Re^2: dynamic perl calls
by dsheroh (Monsignor) on Feb 10, 2009 at 16:11 UTC
    That was my thought as well. This could also be combined with Module::Pluggable to deal with the external files aspect.
Re^2: dynamic perl calls
by TGI (Parson) on Feb 10, 2009 at 19:57 UTC

    Method calls are not subject to strict subs. So you can do:

    use strict; use warnings; my $sub = 'foo'; my @result_set = Dispatch->$sub( qw/bar baz/ ); package Dispatch; sub foo { shift; print @_,"\n"; }


    TGI says moo

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://742764]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2024-04-20 03:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found