![]() |
|< 1 2 3 4 5 >| | ![]() |
45 Einträge, 5 Seiten |
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
#!/usr/bin/perl
use strict;
use warnings;
my $formula = '((1 + 2) * (2 -1)) + (2 * 3) + 5+3';
my %hash = ('*' => \&mal,
'-' => \&minus,
'+' => \&plus,
'/' => \&div,);
while($formula =~ s/\(([^\(]*?)\)/calc($1)/eg){
}
# FORMATIERT AUSGEBEN
print sprintf("%.2f\n", calc($formula));
sub calc{
my ($part) = @_;
while($part =~ s!(\d+)\s*([\*\/])\s*(\d+)!subcalc($1,$2,$3)!eg){};
while($part =~ s!(\d+)\s*([\+\-])\s*(\d+)!subcalc($1,$2,$3)!eg){};
return $part;
}
sub subcalc{
my ($op1,$op,$op2) = @_;
return 0 unless exists($hash{$op});
return $hash{$op}->($op1,$op2);
}
sub mal{
my ($op1,$op2) = @_;
return $op1 * $op2;
}
sub minus{
my ($op1,$op2) = @_;
return $op1 - $op2;
}
sub plus{
my ($op1,$op2) = @_;
return $op1 + $op2;
}
sub div{
my ($op1,$op2) = @_;
return $op1 / $op2;
}
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
(?-imsx:\(([^\(]*?)\))
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
\( '('
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
[^\(]*? any character except: '\(' (0 or more
times (matching the least amount
possible))
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
\) ')'
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
return $hash{$y}->($x1,$x2);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
sub subcalc{
my ($op1,$op,$op2) = @_;
if($op eq '*'){
return mal($op1,$op2);
}
elsif($op eq '/'){
return div($op1,$op2);
}
elsif($op eq '+'){
return plus($op1,$op2);
}
elsif($op eq '-'){
return minus($op1,$op2);
}
else{
return 0;
}
}
![]() |
|< 1 2 3 4 5 >| | ![]() |
45 Einträge, 5 Seiten |