Solution Review: Making a Calculator

Let's see the detailed solution review of the challenge given in the previous lesson.

We'll cover the following

Let’s look at the solution before jumping on to the explanation:

Press + to interact
$num1 = 12.5; # change values
$num2 = 5.1;
$Operator = '-'; # change operator to check for when
print "Number 1 is: $num1 \n";
print "Number 2 is: $num2 \n";
print "Operator is: $Operator \n";
given ($Operator) {
when ('+'){
print "Answer is ";
print $num1+$num2;
}
when ('-') {
print "Answer is ";
print $num1-$num2;
}
when ('*'){
print "Answer is ";
print $num1*$num2;
}
when ('/'){
print "Answer is ";
print $num1/$num2;
}
default{
print "Wrong operator";
}
}

Explanation

We have two variables $num1 and $num2 containing input numbers. We have another variable $Operator containing a character representing one of the desired mathematical operators. The $Operator is passed to the given statement and its value is matched with one of the when statements to perform the corresponding mathematical operation. In case of invalid input in $Operator, the default statement is executed.