1. Is it possible to inject new code into a subroutine that will execute within the lexical scope of the subroutine body? That is, can I take
    sub { BLAH }
    and convert it (programmatically, not by grovelling around in the original definition) into
    sub { BLAH YOUR CODE HERE }
    Specifically, what I have in mind is taking a subroutine that modifies @_—possibly without modifying its original arguments (say, by splicing entries into the middle)—and applying a user-specified function to the resulting mutated array. (A natural thought is some wrapper like
    sub inject { my ( $outer, $inner ) = @_; return sub { $inner->(@_); goto &$outer; } }
    but that doesn't work, since $outer is executing in a different lexical scope.)

    I know that B::Deparse will handle the simple case of functions that don't close over external variables, and Data::Dump::Streamer will handle more cases, but I'm looking for something really robust.

  2. Is there a subroutine uneval such that eval uneval($a) always returns $a? Even if it's possible to do this just when $a is a simple scalar (i.e., not a reference), then I'm happy—but I'd like to preserve any ‘magic’ associated to $a (for example, not lose its numeric value by just stringifying). If one could control the lexical scope in which eval'd strings executed, then this would be easy:
    sub uneval { my ( $a ) = @_; return ( in_current_scope => '$a' ); }
    but I'm not sure how to do it otherwise.

UPDATE: I forgot to mention that I wanted to do the unevaling with lexicals, not globals. It's easy with globals:

our @cache; my $id = 0; sub uneval { $cache[$id++] = $_[0]; return __PACKAGE__ . '::$cache[' . $id . ']'; }

In reply to Modifying subroutines and un-eval-ing by JadeNB

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.