Discipulus has asked for the wisdom of the Perl Monks concerning the following question:
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:
sub new{ my $class = shift; my %opts = @_; unless ( defined $opts{dumper} ){ require Data::Dumper; # + () to avoid Name "Data::Dumper::Dumper" used only +once: possible typo at # full qualified name to avoid runtime error $opts{dumper} = sub{ print +Data::Dumper::Dumper(\$_[0 +]) } } return bless { %opts }, $class; }
I 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?
The 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).
But I can craft execute_command to pass $self as first argument:
sub execute_command{ my $self = shift; my $wanted_command = shift; my @whole_data = @_; $self->{ $wanted_command }->( $self, @whole_data ); }
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*
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: dynamic method creation, dispatch table or pseudo methods?
by choroba (Cardinal) on Apr 18, 2021 at 19:56 UTC | |
| |
|
Re: dynamic method creation, dispatch table or pseudo methods?
by LanX (Saint) on Apr 18, 2021 at 20:33 UTC | |
|
Re: dynamic method creation, dispatch table or pseudo methods?
by perlfan (Parson) on Apr 19, 2021 at 00:51 UTC | |
|
Re: dynamic method creation, dispatch table or pseudo methods?
by Discipulus (Canon) on Apr 20, 2021 at 20:33 UTC | |
by LanX (Saint) on Apr 20, 2021 at 20:49 UTC |