title: Safe.pm base_math as math calculator and new variables
body: <p>I do not want to write my own recursive-descent math parser or think too deeply about grammar, so I am (re-)using the Perl module <a href="https://metacpan.org/pod/Safe" rel="nofollow">Safe.pm</a> as an arithmetic calculator with variables.  My task is to let one anonymous web user A type into a textfield a couple of math expressions, like:</p>
  
  <pre><code>**Input Formula:** $x= 2;  $y=sqrt(2*$x+(25+$x)*$x); $z= log($y); ...
  </code></pre>
  
  <p>Ideally, this should only contain math expressions, but not generic Perl code. Later, I want to use it for web user B:</p>
  
  <pre><code>**Input Print:** you start with x=$x and end with z=$z .  you don't know $a.
  </code></pre>
  
  <p>to &lt;pre&gt; text output that looks like this:</p>
  
  <pre><code>**Output Txt:** you start with x=2 and end with z=2.03 .  you don't know $a.
  </code></pre>
  
  <p>(The fact that $a was not replaced is its own warning.) Ideally, I want to check that my web users have not only not tried to break in, but also have made no syntax errors.</p>
  
  <p>My current Safe.pm-based implementation has drawbacks:</p>
  
  <ul>
  <li><p>I want only <em>math</em> expressions in the first textfield. Alas, <code>:base_math</code> only extends Safe.pm beyond <code>:base_core</code>, so I have to live with the user having access to more than just math algebra expressions. For example, the web users could accidentally try to use a Perl reserved name, define subs, or do who knows what. Is there a better solution that picks off only the recursive descent math grammar parser?  (and, subs like <code>system()</code> should not be permitted math functions!)</p></li>
  <li><p>For the printing, I can just wrap a <code>print "..."</code> around the text and go another Safe eval, but this replaces <code>$a</code> with <code>undef</code>. What I really mean my code to do is to go through the table of newly added variables (<code>$x</code>, <code>$y</code>, and <code>$z</code>) and if they appear unescaped, then replace them; others should be ignored.  I also have to watch carefully here that my guys are not working together to try to escape and type text like <code>"; system("rm -rf *"); print ";</code>, though Safe would catch this particular issue. More likely, A could try to inject some nasty JavaScript for B or who knows what.</p></li>
  </ul>
  
  <p>Questions:</p>
  
  <ol>
  <li>Is Safe.pm the right tool for the job? Perl seems like a heavy cannon here, but not having to reinvent the wheel is nice.</li>
  <li>Can one further restrict Safe.pm to Perl's arithmetic only?</li>
  <li>Is there a "new symbols" table that I can iterate over for substitution?</li>
  </ol>