Perl IFs skipping branches
by IamtheSenate from LinuxQuestions.org on (#6DHGF)
This one is a challenge, I am trying Perl for the first time ever and this is a basic calculation script I want to use in my teaching (replicated in different languages to show syntactical differences). I am becoming unstuck on the IFs used to try and prevent div by zero errors in the divide procedure and similar in the subtract procedure, the interpretor jumps straight to ELSE:
Code:[aaron@orion perl]$ perl mini_calc.pl
20
Error!1
25
0This is my script below:
Code:#!/usr/bin/perl
use warnings;
sub add{
$a = $_[0];
$b = $_[0];
return $a+$b
}
sub subtract{
$c = $_[0];
$d = $_[0];
if($c <=> $d){
return $c-$d;
}
elsif($d <=> $c){
return $d-$c;
}
else{
print "Error!";
}
}
sub multiply{
$e = $_[0];
$f = $_[0];
return $e*$f;
}
sub divide{
$g = $_[0];
$h = $_[0];
if(($g || $h) != 0)
{
if($g <=> $h){
return $g/$h;
}
elsif($h <=> $g){
return $h/$g;
}
}
elsif(($g || $h) == 0){
print "Div by zero error!";
}
}
# call function and then print result to console
$add = add(10,10);
printf $add."\n";
$subtract = subtract(70,10);
printf $subtract."\n";
$multiply = multiply(5,5);
printf $multiply."\n";
$divide = divide(10,5);
printf $divide."\n";If anyone has any pointers please I'd be ever so grateful.
Code:[aaron@orion perl]$ perl mini_calc.pl
20
Error!1
25
0This is my script below:
Code:#!/usr/bin/perl
use warnings;
sub add{
$a = $_[0];
$b = $_[0];
return $a+$b
}
sub subtract{
$c = $_[0];
$d = $_[0];
if($c <=> $d){
return $c-$d;
}
elsif($d <=> $c){
return $d-$c;
}
else{
print "Error!";
}
}
sub multiply{
$e = $_[0];
$f = $_[0];
return $e*$f;
}
sub divide{
$g = $_[0];
$h = $_[0];
if(($g || $h) != 0)
{
if($g <=> $h){
return $g/$h;
}
elsif($h <=> $g){
return $h/$g;
}
}
elsif(($g || $h) == 0){
print "Div by zero error!";
}
}
# call function and then print result to console
$add = add(10,10);
printf $add."\n";
$subtract = subtract(70,10);
printf $subtract."\n";
$multiply = multiply(5,5);
printf $multiply."\n";
$divide = divide(10,5);
printf $divide."\n";If anyone has any pointers please I'd be ever so grateful.