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) :
$S{light}->($self, 10);
instead of
$self->light(10)
(I used %S instead of %mysubs. And i use Moose, so i need to pass $self as an argument).
So, what i did was to use AUTOLOAD, to call these subroutines :
sub 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);
}
which enables me to call
$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
foreach my $name (@names) {
my $name = $S{$name};
}
But then i will also need to put $self as an argument all the time.
What about installing them in the import table : is it cleaner than using AUTOLOAD ?
|