Do you have any pointers to practical code generation (other than compiler optimizers)?

"Practical" is a value judgement, an area where my judgement seems to vary widely with the concensus, so you'll have to make up your own mind.

In terms of the OP's question, I consider this practical. It runs a gnat's appendage slower than a hardcoded unrolled loop, but is 'generic':

sub aveAoA { my( $ref, $n ) = @_; my @sums; my $code = qq[ for my \$i ( 0 .. \$#\$ref ) { ]; $code .= qq[ \$sums[ $_ ] += \$ref->[ \$i ][ $_ ];] for 0 .. $n -1 +; $code .= '}'; eval $code; $sums[ $_ ] /= @{ $ref } for 0 .. $n -1; return @sums; } our $M ||= 1e6; our $N ||= 4; my @data; $#data = $M -1; $data[ $_ ] = [ map int(-10+rand 20), 1.. $N ] for 0 .. $#data; my @sums = aveAoA( \@data, $N );

The eval'd code is determanistic, and in my opinion totally 'safe'. Effectively, it is no different from selectively loading an appropriate subroutine (via import) at runtime except that it avoids having to have pre-written subroutines for every possible contingency.

For existing, well-known and popular modules that already use runtime code generation, see CGI, Catalyst, Template::Toolkit, Moose (though you have to drill down a few levels), Test::More etc.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."

In reply to Re^6: Averaging Elements in Array of Array by BrowserUk
in thread Averaging Elements in Array of Array by neversaint

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.