A recursive subroutine to perform arithmetic. : Recursive « Subroutine « Perl






A recursive subroutine to perform arithmetic.

   
#!/usr/local/bin/perl 

$inputline = <STDIN>; 
$inputline =~ s/^\s+|\s+$//g; 
@list = split (/\s+/, $inputline); 
$result = &rightcalc (0); 
print ("The result is $result.\n"); 

sub rightcalc { 
    my ($index) = @_; 
    my ($result, $operand1, $operand2); 
    
    if ($index+3 == @list) { 
        $operand2 = $list[$index+2]; 
    } else { 
        $operand2 = &rightcalc ($index+2); 
    } 
    $operand1 = $list[$index+1]; 
    if ($list[$index] eq "+") { 
        $result = $operand1 + $operand2; 
    } elsif ($list[$index] eq "*") { 
        $result = $operand1 * $operand2; 
    } elsif ($list[$index] eq "-") { 
       $result = $operand1 - $operand2; 
    } else { 
        $result = $operand1 / $operand2; 
    } 
} 

   
    
    
  








Related examples in the same category

1.Recursive factorial subroutine
2.Recursive fibonacci function.
3.Recursive subroutine
4.Write recursive subroutines
5.calculate 1000th element of standard Fibonacci sequence
6.factorial with recursive function