What I want to do is write a subroutine that returns an optimized sub-routine.

I started with a closure that returns a subroutine based on the inputs, but now I want to make the resultant subroutine optimized. This means taking different routes to achieve my goal depending on the inputs. ( For example, I don't want to divide by 2**n, but just right shift >>n instead, when a user input is a power of 2 )

I'm not sure how to do this using a closure (short of a big ugly if-then-else structure) so I tried to create subroutines like this:
sub Half { my $n = shift; my $SubBody = Power_Of_Two( $n ) ? "return \$_[$[] >> Log2( $n );" : "return int( \$_[$[] / $n );"; my $SubRef; eval "$SubRef = sub { $SubBody }"; return $SubRef; }
but Perl didn't like that very much.

Then I was thinking I could do this as a module and imitate however CGI.pm does it, which involves something Dr. Stein called the _make_tag_func and the DefaultClass. I wasn't quite able to follow the good Doctor's code further then that. So much for imitating it.

So I turn to the Monastery and the Monks who dwell within. I wasn't overly concerned with making this sub-routine exceedingly efficient, so much as I was concerned about maintainability and clarity. I was much more concerned with resultant subroutine being efficient (hence all this optimiziation stuff... other wise my closure worked fine.)

Thanks.


In reply to Fly Subroutines on the Fly by Adam

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.