This is a read-only archive. Find the latest Linux articles, documentation, and answers at the new Linux.com!

Linux.com

Fast, flexible, calculating from the command line

Posted by: Vaida Bogdan on March 12, 2008 12:18 PM
A script I use from the net: calcme "30*27.3"

#!/usr/bin/perl

# Usage calcme <string_to_calculate> [<output_format>]
# Input is a string like (10+3)/7 or "(10 + 3) / 7"
# Output is the calculated result of the string
# Optional formatting can supplied as 2nd parameter.

if (@ARGV == 0 || @ARGV > 2)
{
die("Usage: $0 <\"formula_to_calculate\"> [<output_format>]\n");
}

$format = "";
$calcme = $ARGV[0];
(@ARGV == 2) && ($format = $ARGV[1]);

$output = eval($calcme);

if(@ARGV == 1)
{
print(STDOUT "$output\n");
}
else
{
printf(STDOUT "$format\n", $output);
}
exit(0);

#

Return to Fast, flexible, calculating from the command line