fork(2) download
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. #use feature qw(switch);
  5.  
  6. #print "Test";
  7. my @expression;
  8. my $result;
  9. @expression = split(' ', <>);
  10. $result = simplify(@expression);
  11. if ($result eq "ERROR") {print "ERROR\n"}
  12. else {printf("%.4f", simplify(@expression))}
  13. print "\n";
  14.  
  15. sub simplify {
  16. my @exprs = @_;
  17.  
  18. my $oper = -1;
  19. for (my $index = 0; $index <= $#exprs && $oper == -1; $index++) {
  20. $oper = $index if
  21. ($exprs[$index] eq "+" ||
  22. $exprs[$index] eq "-" ||
  23. $exprs[$index] eq "*" ||
  24. $exprs[$index] eq "/");
  25. }
  26.  
  27. if ($oper == -1 || $oper == 0 || $oper == 1) {return "ERROR"};
  28.  
  29. my @newExpression;
  30.  
  31. for (my $i = 0; $i < $oper - 2; $i++) {
  32. push @newExpression, $exprs[$i];
  33. }
  34.  
  35. push @newExpression, ($exprs[$oper - 2] + $exprs[$oper - 1]) if($exprs[$oper] eq "+");
  36. push @newExpression, ($exprs[$oper - 2] - $exprs[$oper - 1]) if($exprs[$oper] eq "-");
  37. push @newExpression, ($exprs[$oper - 2] * $exprs[$oper - 1]) if($exprs[$oper] eq "*");
  38. push @newExpression, ($exprs[$oper - 2] / $exprs[$oper - 1]) if($exprs[$oper] eq "/");
  39.  
  40. for (my $k = $oper + 1; $k <= $#exprs; $k++) {
  41. push @newExpression, $exprs[$k];
  42. }
  43.  
  44. if ($#newExpression > 0) {return simplify (@newExpression)};
  45. return @newExpression;
  46. }
  47.  
Success #stdin #stdout 0s 17760KB
stdin
1 2 3 /
stdout
ERROR