As others have pointed out, you can do your calculations in Perl. There's no need to call bc
.
But I wanted to look a little closer at the way you're producing your output. You're using a mass of print()
statements. And there are far better approaches.
Firstly, you have statements that look like this:
print "<table border=\"0\">\n";
I know why you have the backslashes there, but doesn't it look ugly to you? You need to escape double-quote characters in double-quoted strings for obvious reasons. But Perl has the qq[...]
operator for cases like this:
print qq[<table border="0">\n];
qq[...]
works just like a double-quoted string but because it doesn't use double-quote characters to delimit the string you don't need to escape the double-quote characters inside the string. Note that you don't even need to use [...]
to delimit the string. You can use almost any character - qq(...)
, qq|...|
and many other options work just as well.
Secondly, why have a separate print()
statement for each line. Whu not combine them into a single print()
statement?
print qq[Content-Type: text/html
<html><body>
<b>Calculator:</b><br/>
<form action="/cgi-bin/calc.cgi" method="GET">
<table border="0">
<tr><td align="right">Expression:</td>
<td><input type="text" name="exp"
value="$exp"/></td></tr>
<tr><td align="right">Result:</td>
<td>$res</td></tr>
<tr><td></td>
<td><input type="submit" value="Evaluate"/></td></tr>
</table></form>
</html></body>];
Notice how you can lose all the explicit \n
and replace them with real newlines embedded in the string. Doesn't that look neater?
In fact most Perl programmers would take that a step further and use a "heredoc" for this:
print <<"ENDHTML";
Content-Type: text/html
<html><body>
<b>Calculator:</b><br/>
<form action="/cgi-bin/calc.cgi" method="GET">
<table border="0">
<tr><td align="right">Expression:</td>
<td><input type="text" name="exp"
value="$exp"/></td></tr>
<tr><td align="right">Result:</td>
<td>$res</td></tr>
<tr><td></td>
<td><input type="submit" value="Evaluate"/></td></tr>
</table></form>
</html></body>
ENDHTML
Also, please consider using the CGI module's header()
method to create your Content-Type header.
And finally, you might look at CGI::Alternatives to learn (among other things) how to move all of your HTML out into a separate file.