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 ?


In reply to Re^2: a loop for creating subroutines? by mascip
in thread a loop for creating subroutines? by mascip

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.