Math/Calc/Parser.pm

filter: Statementstmt 99.0% 303 / 306 Branchbran 91.6% 121 / 132 Conditioncond 84.0% 63 / 75 MC/DCmcdc 65.9% 29 / 44 Subroutinesub 97.8% 92 / 94 Podpod 100% 10 / 10 totaltotal 93.4% 618 / 661 CC 95 SCAR 20.7
CC
95
Cov
95%
parse
26.1
evaluate
19.0
add_functions
11.1
CRAP 7.9
↑ Summary ath.pm »
1 package Math::Calc::Parser;
2 8 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 8 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 8 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 8 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 8 ▶use Exporter ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 8 ▶use Math::Complex ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 8 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 8 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 8 our $VERSION = '1.005';
12 8 our @ISA = 'Exporter';
13 8 our @EXPORT_OK = 'calc';
14 8 our $ERROR;
15  
16 # See disclaimer in Math::Round
17 8 ▶use constant ROUND_HALF => 0.50000000000008;
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 8 ▶BEGIN {
Subroutine BEGIN: called CC=2 SCAR=7.0
20 8 local $@;
21 8 ▶ if (eval { require Math::Random::Secure; 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { require Math::Random::Secure; 1 } }) 8 0 8
22 8 Math::Random::Secure->import('rand');
23 }
24 }
25  
26 {
27 8 my %operators = (
28 '<<' => { assoc => 'left' },
29 '>>' => { assoc => 'left' },
30 '+' => { assoc => 'left' },
31 '-' => { assoc => 'left' },
32 '*' => { assoc => 'left' },
33 '/' => { assoc => 'left' },
34 '%' => { assoc => 'left' },
35 '^' => { assoc => 'right' },
36 '!' => { assoc => 'left' },
37 # Dummy operators for unary minus/plus
38 'u-' => { assoc => 'right' },
39 'u+' => { assoc => 'right' },
40 );
41
42 # Ordered lowest precedence to highest
43 8 my @op_precedence = (
44 ['<<','>>'],
45 ['+','-'],
46 ['*','/','%'],
47 ['u-','u+'],
48 ['^'],
49 ['!'],
50 );
51
52 # Cache operator precedence
53 8 my (%lower_prec, %higher_prec);
54 8 $higher_prec{$_} = 1 for keys %operators;
55 8 foreach my $set (@op_precedence) {
56 48 delete @higher_prec{@$set};
57 48 foreach my $op (@$set) {
58 88 $operators{$op}{equal_to}{$_} = 1 for @$set;
59 88 $operators{$op}{lower_than}{$_} = 1 for keys %higher_prec;
60 88 $operators{$op}{higher_than}{$_} = 1 for keys %lower_prec;
61 }
62 48 $lower_prec{$_} = 1 for @$set;
63 }
64
65 1542 ▶ sub _operator { $operators{shift()} }
Subroutine _operator: called CC=1 SCAR=0.0
66 }
67  
68 {
69 153 ▶ sub _real { Scalar::Util::blessed $_[0] && $_[0]->isa('Math::Complex') ? $_[0]->Re : $_[0] }
Subroutine _real: called CC=3 SCAR=11.7
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($_[0]) && $_[0]->isa('Math::Complex') ? : 0 153 153
Condition66%2/3
builtin::blessed($_[0]) and $_[0]->isa("Math::Complex")
!ll&&!rl&&r
137160
MC/DC0%0/2
builtin::blessed($_[0]) and $_[0]->isa("Math::Complex")
builtin::blessed($_[0]) $_[0]->isa("Math::Complex")
Truth table66%2/3
A and B
A= builtin::blessed($_[0])B= $_[0]->isa("Math::Complex")
ABresult
0X0
100
111
70 14 ▶ sub _each { Scalar::Util::blessed $_[0] && $_[0]->isa('Math::Complex') ? Math::Complex::cplx($_[1]->($_[0]->Re), $_[1]->($_[0]->Im)) : $_[1]->($_[0]) }
Subroutine _each: called CC=3 SCAR=11.0
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($_[0]) && $_[0]->isa('Math::Complex') ? : 1 13 14
Condition100%3/3
builtin::blessed($_[0]) and $_[0]->isa("Math::Complex")
!ll&&!rl&&r
941
MC/DC100%2/2
builtin::blessed($_[0]) and $_[0]->isa("Math::Complex")
builtin::blessed($_[0]) $_[0]->isa("Math::Complex")
Truth table100%3/3
A and B
A= builtin::blessed($_[0])B= $_[0]->isa("Math::Complex")
ABresult
0X0
100
111
71
72 # Adapted from Math::Round
73 4 ▶ sub _round { $_[0] >= 0 ? POSIX::floor($_[0] + ROUND_HALF) : POSIX::ceil($_[0] - ROUND_HALF) }
Subroutine _round: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$_[0] >= 0 ? : 2 2 4
74
75 25 ▶ sub _fact_check {
Subroutine _fact_check: called CC=4 SCAR=13.9
76 25 my $r = _real($_[0]);
77 25 ▶ die 'Factorial of negative number' if $r < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $r < 0 1 24 25
78 24 ▶ die 'Factorial of infinity' if $r == 'inf';
Branch: 1 branch
BranchTrueFalseTotal
if $r == "inf" 1 23 24
79 23 ▶ die 'Factorial of NaN' if $r != $r;
Branch: 1 branch
BranchTrueFalseTotal
if $r != $r 1 22 23
80 22 return $r;
81 }
82
83 2 ▶ sub _atan_factor { Math::BigFloat->new(1)->bsub($_[0]->copy->bpow(2))->bsqrt }
Subroutine _atan_factor: called CC=1 SCAR=0.0
84
85 my %functions = (
86 21 ▶ '<<' => { args => 2, code => sub { _real($_[0]) << _real($_[1]) } },
Subroutine __ANON__: called CC=1 SCAR=0.0
87 22 ▶ '>>' => { args => 2, code => sub { _real($_[0]) >> _real($_[1]) } },
Subroutine __ANON__: called CC=1 SCAR=0.0
88 27 ▶ '+' => { args => 2, code => sub { $_[0] + $_[1] } },
Subroutine __ANON__: called CC=1 SCAR=0.0
89 21 ▶ '-' => { args => 2, code => sub { $_[0] - $_[1] } },
Subroutine __ANON__: called CC=1 SCAR=0.0
90 29 ▶ '*' => { args => 2, code => sub { $_[0] * $_[1] } },
Subroutine __ANON__: called CC=1 SCAR=0.0
91 36 ▶ '/' => { args => 2, code => sub { $_[0] / $_[1] } },
Subroutine __ANON__: called CC=1 SCAR=0.0
92 21 ▶ '%' => { args => 2, code => sub { _real($_[0]) % _real($_[1]) } },
Subroutine __ANON__: called CC=1 SCAR=0.0
93 28 ▶ '^' => { args => 2, code => sub { $_[0] ** $_[1] } },
Subroutine __ANON__: called CC=1 SCAR=0.0
94 '!' => { args => 1,
95 23 ▶ code => sub { my $r = _fact_check($_[0]); my ($n, $f) = (2, 1); $f *= $n++ while $f != 'inf' and $n <= $r; $f },
Subroutine __ANON__: called CC=3 SCAR=11.0
Branch: 1 branch
BranchTrueFalseTotal
$f != "inf" and $n <= $r and do { $f *= $n++ } 44 20 64
Condition66%2/3
$f != "inf" and $n <= $r
!ll&&!rl&&r
02044
MC/DC50%1/2
$f != "inf" and $n <= $r
$f != "inf" $n <= $r
Truth table66%2/3
A and B
A= $f != "inf"B= $n <= $r
ABresult
0X0
100
111
96 2 ▶ bignum_code => sub { my $r = _fact_check($_[0]); $r->copy->bfac } },
Subroutine __ANON__: called CC=1 SCAR=0.0
97 22 ▶ 'u-' => { args => 1, code => sub { -$_[0] } },
Subroutine __ANON__: called CC=1 SCAR=0.0
98 0 ▶ 'u+' => { args => 1, code => sub { +$_[0] } },
Subroutine __ANON__: not called CC=1 SCAR=6.9
99 2 ▶ sqrt => { args => 1, code => sub { Math::Complex::sqrt $_[0] }, bignum_code => sub { $_[0]->copy->bsqrt } },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
100 3 ▶ pi => { args => 0, code => sub { Math::Complex::pi }, bignum_code => sub { Math::BigFloat->bpi } },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
101 5 ▶ 'π' => { args => 0, code => sub { Math::Complex::pi }, bignum_code => sub { Math::BigFloat->bpi } },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
102 0 ▶ i => { args => 0, code => sub { Math::Complex::i }, bignum_code => sub { Math::BigFloat->bnan } },
Subroutine __ANON__: called CC=1 SCAR=1.2
Subroutine __ANON__: not called CC=1 SCAR=1.2
103 2 ▶ e => { args => 0, code => sub { exp 1 }, bignum_code => sub { Math::BigFloat->new(1)->bexp } },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
104 2 ▶ ln => { args => 1, code => sub { Math::Complex::ln $_[0] }, bignum_code => sub { $_[0]->copy->blog } },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
105 2 ▶ log => { args => 1, code => sub { Math::Complex::log10 $_[0] }, bignum_code => sub { $_[0]->copy->blog(10) } },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
106 1 ▶ logn => { args => 2, code => sub { Math::Complex::log($_[0]) / Math::Complex::log($_[1]) }, bignum_code => sub { $_[0]->copy->blog($_[1]) } },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
107 2 ▶ sin => { args => 1, code => sub { Math::Complex::sin $_[0] }, bignum_code => sub { $_[0]->copy->bsin } },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
108 1 ▶ cos => { args => 1, code => sub { Math::Complex::cos $_[0] }, bignum_code => sub { $_[0]->copy->bcos } },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
109 1 ▶ tan => { args => 1, code => sub { Math::Complex::tan $_[0] }, bignum_code => sub { scalar $_[0]->copy->bsin->bdiv($_[0]->copy->bcos) } },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
110 1 ▶ asin => { args => 1, code => sub { Math::Complex::asin $_[0] }, bignum_code => sub { $_[0]->copy->batan2(_atan_factor($_[0])->badd(1))->bmul(2) } },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
111 1 ▶ acos => { args => 1, code => sub { Math::Complex::acos $_[0] }, bignum_code => sub { _atan_factor($_[0])->batan2($_[0]->copy->badd(1))->bmul(2) } },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
112 1 ▶ atan => { args => 1, code => sub { Math::Complex::atan $_[0] }, bignum_code => sub { $_[0]->copy->batan } },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
113 1 ▶ atan2 => { args => 2, code => sub { Math::Complex::atan2 $_[0], $_[1] }, bignum_code => sub { $_[0]->copy->batan2($_[1]) } },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
114 6 ▶ abs => { args => 1, code => sub { abs $_[0] } },
Subroutine __ANON__: called CC=1 SCAR=0.0
115 1 ▶ rand => { args => 0, code => sub { rand }, bignum_code => sub { Math::BigFloat->new(rand) } },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
116 7 ▶ int => { args => 1, code => sub { _each($_[0], sub { int $_[0] }) } },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
117 2 ▶ floor => { args => 1, code => sub { _each($_[0], sub { POSIX::floor $_[0] }) }, bignum_code => sub { $_[0]->copy->bfloor } },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
118 2 ▶ ceil => { args => 1, code => sub { _each($_[0], sub { POSIX::ceil $_[0] }) }, bignum_code => sub { $_[0]->copy->bceil } },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
119 3 ▶ round => { args => 1, code => sub { _each($_[0], sub { _round $_[0] }) }, bignum_code => sub { $_[0]->copy->bfround(0, 'common') },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
120 # Math::BigRat ->as_float broken with upgrading active
121 2 ▶ bigrat_code => sub { local $Math::BigFloat::upgrade = undef; $_[0]->as_float->bfround(0, 'common') } },
Subroutine __ANON__: called CC=1 SCAR=0.0
122 8 );
123
124 17 ▶ sub _default_functions { +{%functions} }
Subroutine _default_functions: called CC=1 SCAR=0.0
125 }
126  
127 {
128 8 my $singleton;
129 565 ▶ sub _instance { Scalar::Util::blessed $_[0] ? $_[0] : ($singleton ||= $_[0]->new) }
Subroutine _instance: called CC=3 SCAR=11.1
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($_[0]) ? : 436 129 565
Condition66%2/3
$singleton ||= $_[0]->new
l!l&&r!l&&!r
12270
MC/DC0%0/2
$singleton ||= $_[0]->new
$singleton $_[0]->new
Truth table66%2/3
A ||= B
A= $singletonB= $_[0]->new
ABresult
1X1
011
000
130 }
131  
132 122 ▶sub calc ($) { _instance(__PACKAGE__)->evaluate($_[0]) }
Subroutine calc: called CC=1 SCAR=0.0
Pod documented
133  
134 18 ▶sub new {
Subroutine new: called CC=4 SCAR=14.0
Pod documented
135 18 my $class = shift;
136 0 ▶ my %params = @_ == 1 ? %{$_[0]} : @_;
Branch: 1 branch
BranchTrueFalseTotal
@_ == 1 ? : 0 18 18
137 18 my $self = bless {}, $class;
138 18 ▶ $self->bignum($params{bignum}) if exists $params{bignum};
Branch: 1 branch
BranchTrueFalseTotal
if exists $params{"bignum"} 1 17 18
139 18 ▶ $self->bigrat($params{bigrat}) if exists $params{bigrat};
Branch: 1 branch
BranchTrueFalseTotal
if exists $params{"bigrat"} 1 17 18
140 18 return $self;
141 }
142  
143 2 ▶sub error { _instance(shift)->{error} }
Subroutine error: called CC=1 SCAR=0.0
Pod documented
144  
145 429 ▶sub bignum {
Subroutine bignum: called CC=3 SCAR=11.0
Pod documented
146 429 my $self = shift;
147 429 ▶ return $self->{bignum} unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 428 1 429
148 1 $self->{bignum} = !!shift;
149 1 ▶ if ($self->{bignum}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"bignum"}) 1 0 1
150 1 require Math::BigInt;
151 1 Math::BigInt->VERSION('1.999722');
152 1 require Math::BigFloat;
153 1 Math::BigFloat->VERSION('1.999722');
154 1 Math::BigInt->upgrade('Math::BigFloat');
155 1 Math::BigFloat->downgrade('Math::BigInt');
156 1 Math::BigFloat->upgrade(undef);
157 }
158 1 return $self;
159 }
160  
161 429 ▶sub bigrat {
Subroutine bigrat: called CC=3 SCAR=11.0
Pod documented
162 429 my $self = shift;
163 429 ▶ return $self->{bigrat} unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 428 1 429
164 1 $self->{bigrat} = !!shift;
165 1 ▶ if ($self->{bigrat}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"bigrat"}) 1 0 1
166 1 require Math::BigInt;
167 1 Math::BigInt->VERSION('1.999722');
168 1 require Math::BigRat;
169 1 Math::BigRat->VERSION('0.260804');
170 1 require Math::BigFloat;
171 1 Math::BigFloat->VERSION('1.999722');
172 1 Math::BigInt->upgrade('Math::BigFloat');
173 1 Math::BigFloat->upgrade('Math::BigRat');
174 1 Math::BigFloat->downgrade(undef);
175 }
176 1 return $self;
177 }
178  
179 1281 ▶sub _functions { shift->{_functions} ||= _default_functions() }
Subroutine _functions: called CC=2 SCAR=7.2
Condition66%2/3
+(shift())->{"_functions"} ||= _default_functions()
l!l&&r!l&&!r
1264170
MC/DC0%0/2
+(shift())->{"_functions"} ||= _default_functions()
+(shift())->{"_functions"} _default_functions()
Truth table66%2/3
A ||= B
A= +(shift())->{"_functions"}B= _default_functions()
ABresult
1X1
011
000
180  
181 10 ▶sub add_functions {
Subroutine add_functions: called CC=11 SCAR=24.1
Pod documented
182 10 my ($self, %functions) = @_;
183 10 foreach my $name (keys %functions) {
184 10 ▶ Carp::croak qq{Function "$name" has invalid name} unless $name =~ m/\A[a-z]\w*\z/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /\A[a-z]\w*\z/i 1 9 10
185 9 my $definition = $functions{$name};
186 9 ▶ $definition = { args => 0, code => $definition } if ref $definition eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $definition eq "CODE" 3 6 9
187 Carp::croak qq{No argument count for function "$name"}
188 9 ▶ unless defined (my $args = $definition->{args});
Branch: 1 branch
BranchTrueFalseTotal
unless defined(my $args = $definition->{"args"}) 1 8 9
189 8 ▶ Carp::croak qq{Invalid argument count for function "$name"}
Branch: 1 branch
BranchTrueFalseTotal
unless $args =~ /\A\d+\z/ and $args >= 0 1 7 8
Condition66%2/3
$args =~ /\A\d+\z/ and $args >= 0
!ll&&!rl&&r
107
MC/DC50%1/2
$args =~ /\A\d+\z/ and $args >= 0
$args =~ /\A\d+\z/ $args >= 0
Truth table66%2/3
A and B
A= $args =~ /\A\d+\z/B= $args >= 0
ABresult
0X0
100
111
190 unless $args =~ m/\A\d+\z/ and $args >= 0;
191 Carp::croak qq{No coderef for function "$name"}
192 7 ▶ unless defined (my $code = $definition->{code});
Branch: 1 branch
BranchTrueFalseTotal
unless defined(my $code = $definition->{"code"}) 1 6 7
193 6 ▶ Carp::croak qq{Invalid coderef for function "$name"} unless ref $code eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $code eq "CODE" 1 5 6
194 5 my %function = (args => $args, code => $code);
195 5 ▶ $function{bignum_code} = $definition->{bignum_code} if defined $definition->{bignum_code};
Branch: 1 branch
BranchTrueFalseTotal
if defined $definition->{"bignum_code"} 0 5 5
196 5 ▶ $function{bigrat_code} = $definition->{bigrat_code} if defined $definition->{bigrat_code};
Branch: 1 branch
BranchTrueFalseTotal
if defined $definition->{"bigrat_code"} 0 5 5
197 5 $self->_functions->{$name} = \%function;
198 }
199 5 return $self;
200 }
201  
202 3 ▶sub remove_functions {
Subroutine remove_functions: called CC=4 SCAR=13.9
Pod documented
203 3 my ($self, @functions) = @_;
204 3 foreach my $name (@functions) {
205 3 ▶ next unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 0 3 3
206 3 ▶ next if defined _operator($name); # Do not remove operator functions
Branch: 1 branch
BranchTrueFalseTotal
if defined _operator($name) 1 2 3
207 2 delete $self->_functions->{$name};
208 }
209 3 return $self;
210 }
211  
212 8 my $token_re = qr{(
213 ( 0x[0-9a-f]+ | 0b[01]+ | 0[0-7]+ ) # Octal/hex/binary numbers
214 | (?: [0-9]*\. )? [0-9]+ (?: e[-+]?[0-9]+ )? # Decimal numbers
215 | [(),] # Parentheses and commas
216 | \w+ # Functions
217 | (?: [-+*/^%!] | << | >> ) # Operators
218 | [^\s\w(),.\-+*/^%!<>]+ # Unknown tokens (but skip whitespace)
219 )}ix;
220  
221 226 ▶sub parse {
Subroutine parse: called CC=26 SCAR=32.6
Pod documented
222 226 my ($self, $expr) = @_;
223 226 $self = _instance($self);
224 226 my $bignum = $self->bignum;
225 226 my $bigrat = $self->bigrat;
226 226 my (@expr_queue, @oper_stack, $binop_possible);
227 226 ▶ while ($expr =~ /$token_re/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /$token_re/g) 851 219 1070
228 851 my ($token, $octal) = ($1, $2);
229
230 # Octal/hex/binary numbers
231 851 ▶ $token = oct $octal if defined $octal and length $octal;
Branch: 1 branch
BranchTrueFalseTotal
if defined $octal and length $octal 0 851 851
Condition33%1/3
defined $octal and length $octal
!ll&&!rl&&r
85100
MC/DC0%0/2
defined $octal and length $octal
defined $octal length $octal
Truth table33%1/3
A and B
A= defined $octalB= length $octal
ABresult
0X0
100
111
232
233 # Implicit multiplication
234 851 ▶ if ($binop_possible and $token ne ')' and $token ne ','
Branch: 1 branch
BranchTrueFalseTotal
if ($binop_possible and $token ne ")" and $token ne "," and not defined _operator($token)) 11 840 851
Condition100%9/9
$binop_possible and $token ne ")" and $token ne "," and not defined _operator($token)
!ll&&!rl&&r
60123911
$binop_possible and $token ne ")" and $token ne ","
!ll&&!rl&&r
5956250
$binop_possible and $token ne ")"
!ll&&!rl&&r
56530256
MC/DC100%4/4
$binop_possible and $token ne ")" and $token ne "," and not defined _operator($token)
$binop_possible $token ne ")" $token ne "," not defined _operator($token)
Truth table100%5/5
A and B and C and not(D)
A= $binop_possibleB= $token ne ")"C= $token ne ","D= not defined _operator($token)
ABCDresult
0XXX0
10XX0
110X0
11100
11111
235 and !defined _operator($token)) {
236 11 _shunt_operator(\@expr_queue, \@oper_stack, '*');
237 }
238
239 851 ▶ if (defined _operator($token)) {
Branch: 6 branches
BranchTrueFalseTotal
if (defined _operator($token)) { } 262 589 851
elsif ($token eq '(') { } 30 559 589
elsif ($token eq ')') { } 30 529 559
elsif ($token eq ',') { } 7 522 529
elsif (&Scalar::Util::looks_like_number($token)) { } 417 105 522
elsif ($token =~ /\A\w+\z/) { } 104 1 105
240 # Detect unary minus/plus
241 262 ▶ if (!$binop_possible and ($token eq '-' or $token eq '+')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $binop_possible and $token eq "-" || $token eq "+") 23 239 262
Condition66%4/6
not $binop_possible and $token eq "-" || $token eq "+"
!ll&&!rl&&r
239023
$token eq "-" or $token eq "+"
l!l&&r!l&&!r
2210
MC/DC33%1/3
not $binop_possible and $token eq "-" || $token eq "+"
not $binop_possible $token eq "-" $token eq "+"
Truth table75%3/4
not(A) and B or C
A= not $binop_possibleB= $token eq "-"C= $token eq "+"
ABCresult
0XX0
1000
11X1
1011
242 23 $token = "u$token";
243 }
244 262 _shunt_operator(\@expr_queue, \@oper_stack, $token);
245 262 ▶ $binop_possible = $token eq '!' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$token eq '!' ? : 26 236 262
246 } elsif ($token eq '(') {
247 30 _shunt_left_paren(\@expr_queue, \@oper_stack);
248 30 $binop_possible = 0;
249 } elsif ($token eq ')') {
250 30 ▶ _shunt_right_paren(\@expr_queue, \@oper_stack)
Branch: 1 branch
BranchTrueFalseTotal
_shunt_right_paren(\@expr_queue, \@oper_stack) or die "Mismatched parentheses\n" 29 1 30
251 or die "Mismatched parentheses\n";
252 29 $binop_possible = 1;
253 } elsif ($token eq ',') {
254 7 ▶ _shunt_comma(\@expr_queue, \@oper_stack)
Branch: 1 branch
BranchTrueFalseTotal
_shunt_comma(\@expr_queue, \@oper_stack) or die "Misplaced comma or mismatched parentheses\n" 6 1 7
255 or die "Misplaced comma or mismatched parentheses\n";
256 6 $binop_possible = 0;
257 } elsif (Scalar::Util::looks_like_number $token) {
258 417 ▶ $token = Math::BigFloat->new($token) if $bignum or $bigrat;
Branch: 1 branch
BranchTrueFalseTotal
if $bignum or $bigrat 80 337 417
Condition100%3/3
$bignum or $bigrat
l!l&&r!l&&!r
3941337
MC/DC100%2/2
$bignum or $bigrat
$bignum $bigrat
Truth table100%3/3
A or B
A= $bignumB= $bigrat
ABresult
1X1
011
000
259 417 _shunt_number(\@expr_queue, \@oper_stack, $token);
260 417 $binop_possible = 1;
261 } elsif ($token =~ m/\A\w+\z/) {
262 104 ▶ die qq{Invalid function "$token"\n} unless exists $self->_functions->{$token};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->_functions->{$token} 4 100 104
263 100 ▶ if ($self->_functions->{$token}{args} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_functions->{$token}{'args'} > 0) { } 70 30 100
264 70 _shunt_function_with_args(\@expr_queue, \@oper_stack, $token);
265 70 $binop_possible = 0;
266 } else {
267 30 _shunt_function_no_args(\@expr_queue, \@oper_stack, $token);
268 30 $binop_possible = 1;
269 }
270 } else {
271 1 die qq{Unknown token "$token"\n};
272 }
273 }
274
275 # Leftover operators go at the end
276 219 ▶ while (@oper_stack) {
Branch: 1 branch
BranchTrueFalseTotal
if (@oper_stack) 242 218 460
277 242 ▶ die "Mismatched parentheses\n" if $oper_stack[-1] eq '(';
Branch: 1 branch
BranchTrueFalseTotal
if $oper_stack[-1] eq "(" 1 241 242
278 241 push @expr_queue, pop @oper_stack;
279 }
280
281 218 return \@expr_queue;
282 }
283  
284 417 ▶sub _shunt_number {
Subroutine _shunt_number: called CC=1 SCAR=0.0
285 417 my ($expr_queue, $oper_stack, $num) = @_;
286 417 push @$expr_queue, $num;
287 417 return 1;
288 }
289  
290 273 ▶sub _shunt_operator {
Subroutine _shunt_operator: called CC=6 SCAR=17.9
291 273 my ($expr_queue, $oper_stack, $oper) = @_;
292 273 my $oper_stat = _operator($oper);
293 273 my $assoc = $oper_stat->{assoc};
294 273 ▶ while (@$oper_stack and defined _operator(my $top_oper = $oper_stack->[-1])) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$oper_stack and defined _operator(my $top_oper = $oper_stack->[-1])) 97 234 331
Condition100%3/3
@$oper_stack and defined _operator(my $top_oper = $oper_stack->[-1])
!ll&&!rl&&r
1874797
MC/DC100%2/2
@$oper_stack and defined _operator(my $top_oper = $oper_stack->[-1])
@$oper_stack defined _operator(my $top_oper = $oper_stack->[-1])
Truth table100%3/3
A and B
A= @$oper_stackB= defined _operator(my $top_oper = $oper_stack->[-1])
ABresult
0X0
100
111
295 97 ▶ if ($oper_stat->{lower_than}{$top_oper}
Branch: 1 branch
BranchTrueFalseTotal
if ($oper_stat->{'lower_than'}{$top_oper} or $assoc eq 'left' and $oper_stat->{'equal_to'}{$top_oper}) { } 58 39 97
Condition100%6/6
$oper_stat->{"lower_than"}{$top_oper} or $assoc eq "left" and $oper_stat->{"equal_to"}{$top_oper}
l!l&&r!l&&!r
391939
$assoc eq "left" and $oper_stat->{"equal_to"}{$top_oper}
!ll&&!rl&&r
132619
MC/DC100%3/3
$oper_stat->{"lower_than"}{$top_oper} or $assoc eq "left" and $oper_stat->{"equal_to"}{$top_oper}
$oper_stat->{"lower_than"}{$top_oper} $assoc eq "left" $oper_stat->{"equal_to"}{$top_oper}
Truth table100%4/4
A or B and C
A= $oper_stat->{"lower_than"}{$top_oper}B= $assoc eq "left"C= $oper_stat->{"equal_to"}{$top_oper}
ABCresult
1XX1
0111
00X0
0100
296 or ($assoc eq 'left' and $oper_stat->{equal_to}{$top_oper})) {
297 58 push @$expr_queue, pop @$oper_stack;
298 } else {
299 39 last;
300 }
301 }
302 273 push @$oper_stack, $oper;
303 273 return 1;
304 }
305  
306 70 ▶sub _shunt_function_with_args {
Subroutine _shunt_function_with_args: called CC=1 SCAR=0.0
307 70 my ($expr_queue, $oper_stack, $function) = @_;
308 70 push @$oper_stack, $function;
309 70 return 1;
310 }
311  
312 30 ▶sub _shunt_function_no_args {
Subroutine _shunt_function_no_args: called CC=1 SCAR=0.0
313 30 my ($expr_queue, $oper_stack, $function) = @_;
314 30 push @$expr_queue, $function;
315 30 return 1;
316 }
317  
318 30 ▶sub _shunt_left_paren {
Subroutine _shunt_left_paren: called CC=1 SCAR=0.0
319 30 my ($expr_queue, $oper_stack) = @_;
320 30 push @$oper_stack, '(';
321 30 return 1;
322 }
323  
324 30 ▶sub _shunt_right_paren {
Subroutine _shunt_right_paren: called CC=8 SCAR=20.8
325 30 my ($expr_queue, $oper_stack) = @_;
326 30 ▶ while (@$oper_stack and $oper_stack->[-1] ne '(') {
Branch: 1 branch
BranchTrueFalseTotal
if (@$oper_stack and $oper_stack->[-1] ne "(") 23 30 53
Condition100%3/3
@$oper_stack and $oper_stack->[-1] ne "("
!ll&&!rl&&r
12923
MC/DC100%2/2
@$oper_stack and $oper_stack->[-1] ne "("
@$oper_stack $oper_stack->[-1] ne "("
Truth table100%3/3
A and B
A= @$oper_stackB= $oper_stack->[-1] ne "("
ABresult
0X0
100
111
327 23 push @$expr_queue, pop @$oper_stack;
328 }
329 30 ▶ return 0 unless @$oper_stack and $oper_stack->[-1] eq '(';
Branch: 1 branch
BranchTrueFalseTotal
unless @$oper_stack and $oper_stack->[-1] eq "(" 1 29 30
Condition66%2/3
@$oper_stack and $oper_stack->[-1] eq "("
!ll&&!rl&&r
1029
MC/DC50%1/2
@$oper_stack and $oper_stack->[-1] eq "("
@$oper_stack $oper_stack->[-1] eq "("
Truth table66%2/3
A and B
A= @$oper_stackB= $oper_stack->[-1] eq "("
ABresult
0X0
100
111
330 29 pop @$oper_stack;
331 29 ▶ if (@$oper_stack and $oper_stack->[-1] ne '('
Branch: 1 branch
BranchTrueFalseTotal
if (@$oper_stack and $oper_stack->[-1] ne "(" and not defined _operator($oper_stack->[-1])) 18 11 29
Condition83%5/6
@$oper_stack and $oper_stack->[-1] ne "(" and not defined _operator($oper_stack->[-1])
!ll&&!rl&&r
8318
@$oper_stack and $oper_stack->[-1] ne "("
!ll&&!rl&&r
8021
MC/DC66%2/3
@$oper_stack and $oper_stack->[-1] ne "(" and not defined _operator($oper_stack->[-1])
@$oper_stack $oper_stack->[-1] ne "(" not defined _operator($oper_stack->[-1])
Truth table75%3/4
A and B and not(C)
A= @$oper_stackB= $oper_stack->[-1] ne "("C= not defined _operator($oper_stack->[-1])
ABCresult
0XX0
10X0
1100
1111
332 and !defined _operator($oper_stack->[-1])) {
333 # Not parentheses or operator, must be function
334 18 push @$expr_queue, pop @$oper_stack;
335 }
336 29 return 1;
337 }
338  
339 7 ▶sub _shunt_comma {
Subroutine _shunt_comma: called CC=5 SCAR=16.1
340 7 my ($expr_queue, $oper_stack) = @_;
341 7 ▶ while (@$oper_stack and $oper_stack->[-1] ne '(') {
Branch: 1 branch
BranchTrueFalseTotal
if (@$oper_stack and $oper_stack->[-1] ne "(") 2 7 9
Condition100%3/3
@$oper_stack and $oper_stack->[-1] ne "("
!ll&&!rl&&r
162
MC/DC100%2/2
@$oper_stack and $oper_stack->[-1] ne "("
@$oper_stack $oper_stack->[-1] ne "("
Truth table100%3/3
A and B
A= @$oper_stackB= $oper_stack->[-1] ne "("
ABresult
0X0
100
111
342 2 push @$expr_queue, pop @$oper_stack;
343 }
344 7 ▶ return 0 unless @$oper_stack and $oper_stack->[-1] eq '(';
Branch: 1 branch
BranchTrueFalseTotal
unless @$oper_stack and $oper_stack->[-1] eq "(" 1 6 7
Condition66%2/3
@$oper_stack and $oper_stack->[-1] eq "("
!ll&&!rl&&r
106
MC/DC50%1/2
@$oper_stack and $oper_stack->[-1] eq "("
@$oper_stack $oper_stack->[-1] eq "("
Truth table66%2/3
A and B
A= @$oper_stackB= $oper_stack->[-1] eq "("
ABresult
0X0
100
111
345 6 return 1;
346 }
347  
348 206 ▶sub evaluate {
Subroutine evaluate: called CC=19 SCAR=29.4
Pod documented
349 206 my ($self, $expr) = @_;
350 206 $self = _instance($self);
351 206 ▶ $expr = $self->parse($expr) unless ref $expr eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $expr eq "ARRAY" 195 11 206
352
353 203 ▶ die "No expression to evaluate\n" unless @$expr;
Branch: 1 branch
BranchTrueFalseTotal
unless @$expr 1 202 203
354
355 202 my $bignum = $self->bignum;
356 202 my $bigrat = $self->bigrat;
357 202 my @eval_stack;
358 202 foreach my $token (@$expr) {
359 728 ▶ die "Undefined token in evaluate\n" unless defined $token;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $token 0 728 728
360 728 ▶ if (exists $self->_functions->{$token}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $self->_functions->{$token}) { } 342 386 728
elsif (&Scalar::Util::looks_like_number($token)) { } 385 1 386
361 342 my $function = $self->_functions->{$token};
362 342 my $num_args = $function->{args};
363 342 ▶ die "Malformed expression\n" if @eval_stack < $num_args;
Branch: 1 branch
BranchTrueFalseTotal
if @eval_stack < $num_args 2 340 342
364 340 ▶ my @args = $num_args > 0 ? splice @eval_stack, -$num_args : ();
Branch: 1 branch
BranchTrueFalseTotal
$num_args > 0 ? : 314 26 340
365 340 my $code = $function->{code};
366 340 ▶ $code = $function->{bignum_code} if ($bignum or $bigrat) and defined $function->{bignum_code};
Branch: 1 branch
BranchTrueFalseTotal
if $bignum || $bigrat and defined $function->{"bignum_code"} 34 306 340
Condition100%6/6
$bignum || $bigrat and defined $function->{"bignum_code"}
!ll&&!rl&&r
2565034
$bignum or $bigrat
l!l&&r!l&&!r
4836256
MC/DC100%3/3
$bignum || $bigrat and defined $function->{"bignum_code"}
$bignum $bigrat defined $function->{"bignum_code"}
Truth table100%5/5
A or B and C
A= $bignumB= $bigratC= defined $function->{"bignum_code"}
ABCresult
00X0
1X00
0100
1X11
0111
367 340 ▶ $code = $function->{bigrat_code} if $bigrat and defined $function->{bigrat_code};
Branch: 1 branch
BranchTrueFalseTotal
if $bigrat and defined $function->{"bigrat_code"} 2 338 340
Condition100%3/3
$bigrat and defined $function->{"bigrat_code"}
!ll&&!rl&&r
304342
MC/DC100%2/2
$bigrat and defined $function->{"bigrat_code"}
$bigrat defined $function->{"bigrat_code"}
Truth table100%3/3
A and B
A= $bigratB= defined $function->{"bigrat_code"}
ABresult
0X0
100
111
368 340 my ($result, $errored, $error);
369 {
370 340 local $@;
371 340 ▶ unless (eval { $result = $code->(@args); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $result = &$code(@args); 1 } }) 4 336 340
372 4 $errored = 1;
373 4 $error = $@;
374 }
375 }
376 340 ▶ if ($errored) {
Branch: 1 branch
BranchTrueFalseTotal
if ($errored) 4 336 340
377 4 ▶ $error = '' unless defined $error;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $error 0 4 4
378 4 $error =~ s/ at .+? line \d+\.$//i;
379 4 chomp $error;
380 4 die qq{Error in function "$token": $error\n};
381 }
382 336 ▶ die qq{Undefined result from function "$token"\n} unless defined $result;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $result 1 335 336
383 {
384 8 ▶ no warnings 'numeric';
Subroutine BEGIN: called CC=1 SCAR=0.0
385 335 push @eval_stack, $result+0;
386 }
387 } elsif (Scalar::Util::looks_like_number $token) {
388 385 push @eval_stack, $token;
389 } else {
390 1 die qq{Invalid function "$token"\n};
391 }
392 }
393
394 194 ▶ die "Malformed expression\n" if @eval_stack > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @eval_stack > 1 1 193 194
395
396 193 return $eval_stack[0];
397 }
398  
399 9 ▶sub try_evaluate {
Subroutine try_evaluate: called CC=2 SCAR=6.9
Pod documented
400 9 my ($self, $expr) = @_;
401 9 $self = _instance($self);
402 9 delete $self->{error};
403 9 undef $ERROR;
404 9 local $@;
405 9 my $result;
406 9 ▶ unless (eval { $result = $self->evaluate($expr); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $result = $self->evaluate($expr); 1 } }) 6 3 9
407 6 chomp(my $error = $@);
408 6 $self->{error} = $ERROR = $error;
409 6 return undef;
410 }
411 3 return $result;
412 }
413  
414 8 1;
415  
416 =encoding utf8
417  
418 =head1 NAME
419  
420 Math::Calc::Parser - Parse and evaluate mathematical expressions
421  
422 =head1 SYNOPSIS
423  
424 use Math::Calc::Parser 'calc';
425 use utf8; # for π in source code
426
427 my $result = calc '2 + 2'; # 4
428 my $result = calc 'int rand 5'; # Random integer between 0 and 4
429 my $result = calc 'sqrt -1'; # i
430 my $result = calc '0xff << 2'; # 1020
431 my $result = calc '1/0'; # Division by 0 exception
432
433 # Class methods
434 my $result = Math::Calc::Parser->evaluate('2 + 2'); # 4
435 my $result = Math::Calc::Parser->evaluate('3π^2'); # 29.608813203268
436 my $result = Math::Calc::Parser->evaluate('0.7(ln 4)'); # 0.970406052783923
437
438 # With more advanced error handling
439 my $result = Math::Calc::Parser->try_evaluate('rand(abs'); # undef (Mismatched parentheses)
440 if (defined $result) {
441 print "Result: $result\n";
442 } else {
443 print "Error: ".Math::Calc::Parser->error."\n";
444 }
445
446 # Or as an object for more control
447 my $parser = Math::Calc::Parser->new;
448 $parser->add_functions(triple => { args => 1, code => sub { $_[0]*3 } });
449 $parser->add_functions(pow => { args => 2, code => sub { $_[0] ** $_[1] });
450 $parser->add_functions(one => sub { 1 }, two => sub { 2 }, three => sub { 3 });
451
452 my $result = $parser->evaluate('2(triple one)'); # 2*(1*3) = 6
453 my $result = $parser->evaluate('pow(triple two, three)'); # (2*3)^3 = 216
454 my $result = $parser->try_evaluate('triple triple'); # undef (Malformed expression)
455 die $parser->error unless defined $result;
456
457 $parser->remove_functions('π', 'e');
458 $parser->evaluate('3π'); # Invalid function exception
459
460 # Arbitrary precision calculations - use only in a controlled environment
461 $parser->bignum(1);
462 my $result = $parser->evaluate('30!'); # 265252859812191058636308480000000
463 my $result = $parser->evaluate('atan pi'); # 1.262627255678911683444322083605698343509
464
465 # Rational number calculations - use only in a controlled environment
466 $parser->bigrat(1);
467 my $result = $parser->evaluate('3 / 9'); # 1/3
468 my $result = $parser->evaluate('3 >> 2'); # 3/4
469  
470 =head1 DESCRIPTION
471  
472 L<Math::Calc::Parser> is a simplified mathematical expression evaluator with
473 support for complex and trigonometric operations, implicit multiplication, and
474 perlish "parentheses optional" functions, while being safe for arbitrary user
475 input. It parses input strings into a structure based on
476 L<Reverse Polish notation|http://en.wikipedia.org/wiki/Reverse_Polish_notation>
477 (RPN), and then evaluates the result. The list of recognized functions may be
478 customized using L</"add_functions"> and L</"remove_functions">.
479  
480 =head1 FUNCTIONS
481  
482 =head2 calc
483  
484 use Math::Calc::Parser 'calc';
485 my $result = calc '2+2';
486
487 $ perl -MMath::Calc::Parser=calc -E 'say calc "2+2"'
488 $ perl -Math -e '2+2'
489  
490 Compact exportable function wrapping L</"evaluate"> for string expressions.
491 Throws an exception on error. See L<ath> for easy compact one-liners.
492  
493 =head1 ATTRIBUTES
494  
495 These attributes can only be set on instantiated objects.
496  
497 =head2 bignum
498  
499 my $bool = $parser->bignum;
500 $parser = $parser->bignum($bool);
501  
502 Enable support for arbitrary precision numbers using L<Math::BigInt> and
503 L<Math::BigFloat>. This will avoid losing precision when working with floats or
504 large integers, but see L</"BIGNUM CAVEATS">.
505  
506 =head2 bigrat
507  
508 my $bool = $parser->bigrat;
509 $parser = $parser->bigrat($bool);
510  
511 Enable support for precise rational numbers using L<Math::BigRat>. This will
512 avoid losing precision when working with integer divison and similar
513 operations, and will result in output like C<3/7> where possible, but see
514 L</"BIGNUM CAVEATS">.
515  
516 =head1 METHODS
517  
518 Aside from C<add_functions> and C<remove_functions>, all methods can be called
519 as class methods, and will act on a singleton object with the default functions
520 available.
521  
522 =head2 new
523  
524 my $parser = Math::Calc::Parser->new;
525 my $parser = Math::Calc::Parser->new(bignum => 1);
526  
527 Creates a new L<Math::Calc::Parser> object.
528  
529 =head2 parse
530  
531 my $parsed = Math::Calc::Parser->parse('5 / e^(i*pi)');
532 my $parsed = $parser->parse('3pi');
533  
534 Parses a mathematical expression. On success, returns an array reference
535 representation of the expression in RPN notation which can be passed to
536 L</"evaluate">. Throws an exception on failure.
537  
538 =head2 evaluate
539  
540 my $result = Math::Calc::Parser->evaluate($parsed);
541 my $result = Math::Calc::Parser->evaluate('log rand 7');
542 my $result = $parser->evaluate('round 13/3');
543  
544 Evaluates a mathematical expression. The argument can be either an arrayref
545 from L</"parse"> or a string expression which will be passed to L</"parse">.
546 Returns the result of the expression on success or throws an exception on
547 failure.
548  
549 =head2 try_evaluate
550  
551 if (defined (my $result = Math::Calc::Parser->try_evaluate('floor 2.5'))) {
552 print "Result: $result\n";
553 } else {
554 print "Error: ".Math::Calc::Parser->error."\n";
555 }
556
557 if (defined (my $result = $parser->try_evaluate('log(5'))) {
558 print "Result: $result\n";
559 } else {
560 print "Error: ".$parser->error."\n";
561 }
562  
563 Same as L</"evaluate"> but instead of throwing an exception on failure, returns
564 undef. The L</"error"> method can then be used to retrieve the error message.
565 The error message for the most recent L</"try_evaluate"> call can also be
566 retrieved from the package variable C<$Math::Calc::Parser::ERROR>.
567  
568 =head2 error
569  
570 my $result = Math::Calc::Parser->try_evaluate('(i');
571 die Math::Calc::Parser->error unless defined $result;
572 my $result = $parser->try_evaluate('2//');
573 die $parser->error unless defined $result;
574  
575 Returns the error message after a failed L</"try_evaluate">.
576  
577 =head2 add_functions
578  
579 $parser->add_functions(
580 my_function => { args => 5, code => sub { return grep { $_ > 0 } @_; } },
581 other_function => sub { 20 },
582 bignum_function => { args => 1, code => sub { 2 ** $_[0] }, bignum_code => sub { Math::BigInt->new(2)->bpow($_[0]) } },
583 );
584  
585 Adds functions to be recognized by the parser object. Keys are function names
586 which must start with an alphabetic character and consist only of
587 L<word characters|http://perldoc.perl.org/perlrecharclass.html#Word-characters>.
588 Values are either a hashref containing C<args> and C<code> keys, or a coderef
589 that is assumed to be a 0-argument function. C<args> must be an integer greater
590 than or equal to C<0>. C<code> or the passed coderef will be called with the
591 numeric operands passed as parameters, and must either return a numeric result
592 or throw an exception. Non-numeric results will be cast to numbers in the usual
593 perl fashion, and undefined results will throw an evaluation error.
594  
595 Alternate implementations to be used when L</"bignum"> or L</"bigrat"> is
596 enabled can be passed as C<bignum_code> and C<bigrat_code> respectively.
597 C<bignum_code> will also be used for L</"bigrat"> calculations if
598 C<bigrat_code> is not separately defined; it is not common that these will need
599 separate implementations.
600  
601 =head2 remove_functions
602  
603 $parser->remove_functions('rand','nonexistent');
604  
605 Removes functions from the parser object if they exist. Can be used to remove
606 default functions as well as functions previously added with
607 L</"add_functions">.
608  
609 =head1 OPERATORS
610  
611 L<Math::Calc::Parser> recognizes the following operators with their usual
612 mathematical definitions.
613  
614 +, -, *, /, %, ^, !, <<, >>
615  
616 Note: C<+> and C<-> can represent both binary addition/subtraction and unary
617 negation.
618  
619 =head1 DEFAULT FUNCTIONS
620  
621 L<Math::Calc::Parser> parses several functions by default, which can be
622 customized using L</"add_functions"> or L</"remove_functions"> on an object
623 instance.
624  
625 =over
626  
627 =item abs
628  
629 Absolute value.
630  
631 =item acos
632  
633 =item asin
634  
635 =item atan
636  
637 Inverse sine, cosine, and tangent.
638  
639 =item atan2
640  
641 Two-argument inverse tangent of first argument divided by second argument.
642  
643 =item ceil
644  
645 Round up to nearest integer.
646  
647 =item cos
648  
649 Cosine.
650  
651 =item e
652  
653 Euler's number.
654  
655 =item floor
656  
657 Round down to nearest integer.
658  
659 =item i
660  
661 Imaginary unit.
662  
663 =item int
664  
665 Cast (truncate) to integer.
666  
667 =item ln
668  
669 Natural log.
670  
671 =item log
672  
673 Log base 10.
674  
675 =item logn
676  
677 Log with arbitrary base given as second argument.
678  
679 =item pi
680  
681 π
682  
683 =item π
684  
685 π (this must be the decoded Unicode character)
686  
687 =item rand
688  
689 Random value between 0 and 1 (exclusive of 1). Uses L<Math::Random::Secure> if
690 installed.
691  
692 =item round
693  
694 Round to nearest integer, with halfway cases rounded away from zero. Due to
695 bugs in L<Math::BigRat>, precision may be lost with L</"bigrat"> enabled.
696  
697 =item sin
698  
699 Sine.
700  
701 =item sqrt
702  
703 Square root.
704  
705 =item tan
706  
707 Tangent.
708  
709 =back
710  
711 =head1 CAVEATS
712  
713 While parentheses are optional for functions with 0 or 1 argument, they are
714 required when a comma is used to separate multiple arguments.
715  
716 Due to the nature of handling complex numbers, the evaluated result may be a
717 L<Math::Complex> object. These objects can be directly printed or used in
718 numeric operations but may be more difficult to use in comparisons.
719  
720 Operators that are not defined to operate on complex numbers will return the
721 result of the operation on the real components of their operands. This includes
722 the operators C<E<lt>E<lt>>, C<E<gt>E<gt>>, C<%>, and C<!>.
723  
724 =head1 BIGNUM CAVEATS
725  
726 The L<Math::BigInt>, L<Math::BigFloat>, and L<Math::BigRat> packages are useful
727 for working with numbers without losing precision, and can be used by this
728 module by setting the L</"bignum"> or L</"bigrat"> attributes, but care should
729 be taken. They will perform significantly slower than native Perl numbers, and
730 can result in an operation that does not terminate or one that uses up all your
731 memory.
732  
733 Additionally, similar to when using the L<bignum> or L<bigrat> pragmas, the
734 auto-upgrading and downgrading behavior of these modules can only be set
735 globally, so enabling these options will affect all other uses of these modules
736 in your program. For the same reason, it is not recommended to enable both
737 L</"bignum"> and L</"bigrat"> in the same program.
738  
739 The evaluated result may be a L<Math::BigInt>, L<Math::BigFloat>,
740 L<Math::BigRat>, or other similar type of object. These objects can be printed
741 and behave normally as numbers.
742  
743 L<Math::BigFloat> defaults to rounding values at 40 digits in division. This
744 can be controlled by setting the global L<Math::BigFloat/"ACCURACY AND PRECISION">,
745 but may have a large impact on performance and memory usage.
746  
747 Complex math is incompatible with L</"bignum"> and L</"bigrat"> and will likely
748 result in NaN.
749  
750 =head1 BUGS
751  
752 Report any issues on the public bugtracker.
753  
754 =head1 AUTHOR
755  
756 Dan Book, C<dbook@cpan.org>
757  
758 =head1 COPYRIGHT AND LICENSE
759  
760 Copyright 2015, Dan Book.
761  
762 This library is free software; you may redistribute it and/or modify it under
763 the terms of the Artistic License version 2.0.
764  
765 =head1 SEE ALSO
766  
767 L<Math::Complex>
↑ Summary ath.pm »