Arithmetic.pm

filter: Statementstmt 100% 19 / 19 Branchbran 50.0% 1 / 2 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod 100% 1 / 1 totaltotal 96.3% 26 / 27 CC 2 SCAR 3.0
CC
2
Cov
95%
parse_arithmetic
2.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.3
« Arithmetic/Pegex.pm ↑ Summary Arithmetic/NoHash.pm »
1 package PERLANCAR::Parse::Arithmetic;
2  
3 2 our $DATE = '2016-06-18'; # DATE
4 2 our $VERSION = '0.004'; # VERSION
5  
6 2 ▶use 5.010001;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 2 my %match;
11  
12 2 ▶use Exporter qw(import);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 2 our @EXPORT_OK = qw(parse_arithmetic);
14  
15 3 ▶sub parse_arithmetic {
Subroutine parse_arithmetic: called CC=2 SCAR=7.1
Pod documented
16 state $RE =
17 qr{
18 (?&TOP)
19 (?{
20 $match{top} = $^R;
21 })
22  
23 (?(DEFINE)
24  
25 (?<TOP>
26 ^\s* (?&EXPR) \s*$
27 )
28  
29 (?<EXPR>
30 (?&MULT_EXPR)
31 (?{
32 $match{add} = $^R
33 })
34 (?: \s* ([+-])
35 (?{
36 $match{op_add} = $^N;
37 })
38 \s* (?&MULT_EXPR)
39 (?{
40 $match{add} = $match{op_add} eq '+' ? $match{add} + $^R : $match{add} - $^R;
41 })
42 )*
43 )
44  
45 (?<MULT_EXPR>
46 (?&POW_EXPR)
47 (?{
48 $match{mult} = $^R;
49 })
50 (?: \s* ([*/])
51 (?{
52 $match{op_mult} = $^N;
53 }) \s*
54 (?&POW_EXPR)
55 (?{
56 $match{mult} = $match{op_mult} eq '*' ? $match{mult} * $^R : $match{mult} / $^R;
57 })
58 )*
59 )
60  
61 (?<POW_EXPR>
62 (?&TERM)
63 (?{
64 $match{pow} = [$^R];
65 })
66 (?: \s* \*\* \s* (?&TERM)
67 (?{
68 unshift @{$match{pow}}, $^R;
69 })
70 )*
71 (?{
72 # because ** is right-to-left, we collect first then
73 # apply from right to left
74 my $res = $match{pow}[0];
75 for (1..$#{$match{pow}}) {
76 $res = $match{pow}[$_] ** $res;
77 }
78 $res;
79 })
80 )
81  
82 (?<TERM>
83 \( \s* (?&EXPR)
84 (?{
85 $^R;
86 })
87 \s* \)
88 | (?&LITERAL)
89 (?{
90 $^R;
91 })
92 )
93  
94 (?<LITERAL>
95 (-?(?:\d+|\d*\.\d+))
96 (?{
97 $^N;
98 })
99 )
100 )
101 3 }x;
102 3 ▶ $_[0] =~ $RE or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ /$RE/ or return undef 3 0 3
103 3 $match{top};
104 }
105  
106 2 1;
107 # ABSTRACT: Parse arithmetic expmatchsion
108  
109 __END__
« Arithmetic/Pegex.pm ↑ Summary Arithmetic/NoHash.pm »