Sei sulla pagina 1di 2

2.

Write a Perl script which will read a mathematical sentence from the user, evaluate the result, and
print the result to the screen. For example, if the user types 2 + 4 = the program will output 6. All
formulas will be given in the format Operand_1 Operator Operand_2 = The characters in the formulas
may or may not be separated by whitespace. The operators that must be supported are: '+', '-', '/', '*',
'%'. The values of the operands may be negative (in which case the minus sign will be immediately in
front of the operand, with no spaces). Any whole numbers should be supported as an operand.

CODE:

($in)=@ARGV;
$in=~/(.)(\d*)([-+\/*%])(.)(\d*)/;
$a=$1;
$b=$2;
$c=$3;
$d=$4;
$e=$5;
$x=$a.$b;
$y=$d.$e;

if ($c eq "+")
{
$result=$x+$y;
}
if ($c eq "-")
{
$result=$x-$y;
}
if ($c eq "/")
{
$result=$x/$y;
}
if ($c eq "*")
{
$result=$x*$y;
}
if ($c eq "%")
{
$result=$x%$y;
}
print "Result: $result\n";

OUTPUT:

Potrebbero piacerti anche