Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!


Click here to return to the 'even better and simpler way' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
even better and simpler way
Authored by: SOX on Jul 09, '07 09:34:25AM
Perl has a solution ready made for you and it's built in and does what you want. namely at the command line type:
perl -ne 'print eval($_)."\n"'
Now in case that's too much trouble, just create an alias like this.
alias calc perl\ \-ne\ \'print\ eval\(\$_\)\.\"\\n\"\'
This will give you a perl interpreter at the command line that executes any commands you type in. THis saves you the hassle of having to type "print" before your entries or worrying about parentheses from confusing the print statement. All the usual math function like sine and cosine still function. want fixed decimal places well then here you go:
alias calc2 perl\ \-ne\ \'printf\ \"\%.2f\\n\"\,eval\(\$_\)\'
This will give you 2 decimal places.

[ Reply to This | # ]
improved version:
Authored by: SOX on Jul 09, '07 10:40:23AM
Here's an improved version
alias calc perl\ \-ne\'\$bb\=\$x\;\$z\[\+\+\$i\]\=\$x\=eval\(\$_\)\;print\"\[\$i\]\\t\$x\\n\"\;\$y\=\$bb\'
This defines three variables $x, $y, and @z. results of the previous two commands, plus a stack of all the previous results.

>calc
27+18
[1]     45
3.3+7
[2]     10.3
$y             # the second to last result value
[3]     45
17+14
[4]     31
$x+9          # use the last result value
[5]     40
$z[2]-1       # use the very second result value
[6]     9.3
"@z"           # see the whole history
[7]      45 10.3 45 31 40 9.3


[ Reply to This | # ]
even better and simpler way
Authored by: rjetton on Jul 11, '07 05:37:46PM
You should look into the purpose behind taint checking before proceeding. Some of this eval() stuff can be dangerous! Imagine... blindly executing anything that a user types as input to a perl script! And if you don't get it, think about some of perl's builtin functions that don't do math. Like unlink(), maybe?

[ Reply to This | # ]