in reply to Re: a loop for creating subroutines?
in thread a loop for creating subroutines?
More solutions, cool :-)
I see that lanX's answer is the "good" clean answer, but i don't like it as a stand-alone answer, as the code then looks ugly (i forgot to say it's a method, not a function) :
instead of$S{light}->($self, 10);
(I used %S instead of %mysubs. And i use Moose, so i need to pass $self as an argument).$self->light(10)
So, what i did was to use AUTOLOAD, to call these subroutines :
which enables me to callsub AUTOLOAD { my $self = shift; my @args = @_; # Retrieve the method name, without the Package name my $name = our $AUTOLOAD; $name =~ s/.*://; # Check if this is one of the functions we declared croak "Undefined method : $name" if !$S{$name}; # Call the appropriate method return $S{$name}->($self, @args); }
$obj->light(10);
Now, the question is : is that clean, and are there "cleaner" (and why) solutions.
I must say i'm not in love with the 'eval' solution ( but it works :-) ).
Would it be cleaner to do
But then i will also need to put $self as an argument all the time.foreach my $name (@names) { my $name = $S{$name}; }
What about installing them in the import table : is it cleaner than using AUTOLOAD ?
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^3: a loop for creating subroutines?
by philiprbrenan (Monk) on Aug 27, 2012 at 20:52 UTC | |
Re^3: a loop for creating subroutines?
by Anonymous Monk on Aug 28, 2012 at 06:58 UTC | |
Re^3: a loop for creating subroutines?
by LanX (Saint) on Aug 28, 2012 at 08:47 UTC |
In Section
Seekers of Perl Wisdom