2017-11-15T15:07:00 GwenDragonDas Problem ist ja, dass der ganze Ausdruck eingelesen werden mus, um dann die Operatoren in ihrer richtigen Rangfolge zu verwenden.
1 2 3 4 5 6 7 8 9 10 11 12
#!/usr/bin/perl use warnings; use strict; my $a = 10; my $b = 3; my $c = 5; my $d = "\$a + \$b * \$c"; print "$d\n"; print eval($d) . "\n";
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
my $r = '3 + 5 * 2 - 3 * 4'; sub summe { my ($left, $right) = @_; my $left_num = evaluate($left); my $right_num = evaluate($right); return $left_num + $right_num; } sub differenz { my ($left, $right) = @_; my $left_num = evaluate($left); my $right_num = evaluate($right); return $left_num - $right_num; } sub produkt { my ($left, $right) = @_; my $left_num = evaluate($left); my $right_num = evaluate($right); return $left_num * $right_num; } sub quotient { my ($left, $right) = @_; my $left_num = evaluate($left); my $right_num = evaluate($right); return $left_num / $right_num; } sub evaluate { my $str = shift; $str =~ s/^\s*(.*?)\s*$/$1/; say $str; if ($str =~ /^\d+$/) { return $str; } my ($left, $typ, $right); ($left, $typ, $right) = split(/([\-\+])/, $str, 2); if (not defined $typ) { ($left, $typ, $right) = split(/([\*\/])/, $str, 2); } if (defined $typ) { if ($typ eq '+') { return summe($left, $right); } elsif ($typ eq '-') { return differenz($left, $right); } elsif ($typ eq '*') { return produkt($left, $right); } elsif ($typ eq '/') { return quotient($left, $right); } } else { die '?????????'; } } say "Ergebnis: ".evaluate($r);
1 while $str =~ s/\(([^()]+)\)/evaluate($1)/e;