TermMiator TermMiator - 3 months ago 7
Perl Question

Why does my Perl calculator always return 0?

Hello I new to Perl and I learning the basics and the idea is write a calculator that can run, and perform the basic operations like multiplication, addition, ... Using as well RegEx.

Now the problem is that I'm getting

0
no matter what and I was wondering if any one can check the code and maybe tell me if I did something wrong also I will like to ask about
chomp
is it better than
STDIN
?

My Perl code is this:

sub only_number
{
($num) = @_;

do{
print "Type a Number: ";
$num = <STDIN>;
if($num =~ /\D+.*\n$/){
print "Thats is not a number. >:[ \n";
}
} until($num = $num + 0);
};
&only_number($num1);

do{
print "What do you want to do? ";
$operator = <STDIN>;
if($operator !~ /\/|\*|\-|\+/){
print "Thats not a valid character (-_-;).\n"
}
} until ($operator =~ /\/|\*|\-|\+/);

&only_number($num2);

if($operator eq "*\n"){
$result = $num1*$num2;
}
elsif($operator eq "/\n"){
$result = $num1/$num2;
}
elsif($operator eq "+\n"){
$result = $num1+$num2;
}
elsif($operator eq "-\n"){
$result = $num1-$num2;
}
print "your answer is $result\n";

exit;


Am I missing something?

Answer

Your function only_number did not return value nor did it change its argument actually. You program should work this way.

sub only_number
{
    my $num;
    while(1) {
            print "Type a Number: ";
            chomp($num = <STDIN>);
            if($num !~ /^\d+$/){
                    print "Thats is not a number. >:[ \n";
                    next;

            }
            return $num;
    }
};

my $num1 = only_number();

my $operator;
while(1) {
    print "What do you want to do? ";
    chomp($operator = <STDIN>);
    if($operator !~ /\/|\*|\-|\+/){
            print "Thats not a valid character (-_-;).\n"
            next;
    }
    last;
 }

 my $num2 = only_number();

 if($operator eq "*"){
    $result = $num1*$num2;
 }
 elsif($operator eq "/"){
    $result = $num1/$num2;
 }
 elsif($operator eq "+"){
    $result = $num1+$num2;
 }
 elsif($operator eq "-"){
    $result = $num1-$num2;
 }
 print "your answer is $result\n";

exit;
Comments