There is a vast difference between eval with a string and eval with a block. String-eval will evaluate the string, while block eval will execute the block and catch any exceptions raised in there. What you (seem to) want is the string form of eval:

use strict; my $x = 3; my $y = "2 * $x"; # interpolation here sets y to '2 * 3' already! my $z = eval $y; # $z is 6 now print "\$x is $x"; print "\$y is $y"; print "\$z is $z";

More likely though, in the long run, you will want to ditch eval and build your own parser for mathematical expressions. There are two or three approaches to such parsers, the best documented way is the way Dominus describes in his book Higher Order Perl. The second approach would be to use Parse::RecDescent, which allows a "natural" approach to parsing but has horribly bad error messages whenever you mess up your input. The third approach is to use Parse::YAPP, which is mostly like the yacc compiler builder, but for Perl. I found yacc (and P:YAPP) to be unapproachable first, but the speed made up for the steeper learning curve.


In reply to Re: nested variable resolution by Corion
in thread nested variable resolution by mpettis

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.