"be consistent" | |
PerlMonks |
dynamic method creation, dispatch table or pseudo methods?by Discipulus (Canon) |
on Apr 18, 2021 at 19:22 UTC ( [id://11131437]=perlquestion: print w/replies, xml ) | Need Help?? |
Discipulus has asked for the wisdom of the Perl Monks concerning the following question:
Hello folks, I'm planning a little module ( an interactive cli using Term::ReadLine ) but I want make possible for the module user to add some method in the constructor, no Moo* usage is planned so I'd like to see basic perl approaches. At the moment I have soemthing like:
dynamic method creationI can build up a method dynamically with *{"${class}::${meth}"} = sub { my $self = shift; ... } I imagine I can do this directly in the new constructor, right? There are drawbacks or pitfall I overlooked in this approach?
dispatch tableThe above code for new adds not a method but a property of the object actually being a callable sub: after I can access it like in $obj->{dumper}->([1,2,{a=>42}]) I can expand this providing to the module user a method to add commends: use Data::Dump; $obj->add_command( {descr=>'a dumper', command => sub{ dd $_[0] } ) This seems to me a simpler approach and I cant imagine drawbacks using it. The only one I can imagine is that not being a method I cannot have $self available inside this calls (even if I dont know atm if will be needed).
pseudo methods?But I can craft execute_command to pass $self as first argument:
This leads to something like a pseudo method; is this too dirty? Has other drawbacks? Do you expulse me from perlmonks if I write it down? :) In addition: if new will be as above in the final module, should I add Data::Dumper to prerequisites? I'd say yes but... if not Data::Dumper but Math::Mersenne::Primes was the case? I must add it to prerequisites even if there is the chance it will be never loaded? L*
There are no rules, there are no thumbs.. Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Back to
Seekers of Perl Wisdom
|
|