Can I "eval" something in such a way that any changes made to variables within the "eval" are forgotten? I would like a function EVAL() so that, for instance,

my $i = 0; EVAL("++$i; Do_Something()"); print "\$i equals $i\n";

would print "i equals 0", assuming Do_Something() does not change $i. We do not know in advance what variables may be used in the EVAL parameter.

Update: solution using threads given in Re^3, thanks to b4swine!

The reason I ask is that I am writing a Perl-Tk calculator with command and answer lines (called Command and Answer below). Command takes input from the keyboard but also from GUI buttons that update Answer like typical calculator buttons.

Keyboard entry is eval'ed (after some calculator-friendly preprocessing) as a Perl expression, and updates Answer only when special keys such as Return are encountered. However GUI buttons should update Answer more frequently, leading to difficulties. For instance, if $i has value zero, the line

(++$i)+1;

should of course give Answer "2". However if the ")+1" substring were entered via GUI buttons, then the following should happen:

")": evaluate first part, give Answer "1";

"*": do nothing for now;

"1": re-evaluate the whole string, and give Answer "2" (not "3" even though ++$i was evaluated again).

The whole string must be re-evaluated at this last step, since the user might have changed the contents of Command via the keyboard.

My aim is to make an app that perfectly mimics a typical calculator. Full compatibility with Perl is not desired, but I want scalar purely-numeric Perl expressions to evaluate correctly (except for some fairly useless expressions that are pre-interpreted in a calculator friendly way).


In reply to 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.