Thanks for the quick response, which seems very promising especially as I hadn't delved into namespaces before now. Unfortunately, while it solves one half of the problem (protecting outer copies of the variables), it does not solve the other (copying the outer variables to the inner namespace).

For instance if I initialize $i to 3 via "$i=3;" or "local $i=3;" early in main, and then feed line input to EVAL via:

for (;$line=<>;) { $v = EVAL($line); print "answer is $v\n"; }
then $i is initially undefined in the local package, so the input "++$i" gives "answer is 1" every time, rather than the desired "answer is 4" every time.

I would like to import from main all variables that are used in this particular call to EVAL(). More precisely, when EVAL($line) encounters a variable ($i, say) while evaluating $line:

(b) if $i is already defined in the local namespace, use that value (could happen if $i were assigned earlier in the evaluation of the same $line).

(a) otherwise, import $i from main;

If the only solution is to explicitly import named variables we would need to parse $line to discover what variables it uses. This seems like an ugly non-ideal solution but it is feasible as a last resort because I only want a solution that works right for most scalar purely numeric expressions, rather than one that works when $line includes strings, function calls, etc. But is there a more beautiful solution?


In reply to Re^2: eval something using private copy of variables by gboole
in thread eval something using private copy of variables by gboole

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.