File Coverage

examples/eval-expr.pl
Criterion Covered Total %
statement 42 42 100.0
branch n/a
condition n/a
subroutine 15 15 100.0
pod n/a
total 57 57 100.0


line stmt bran cond sub pod time code
1             #!/usr/bin/perl
2              
3 1     1   344 use strict;
  1         2  
  1         25  
4 1     1   4 use warnings;
  1         1  
  1         29  
5              
6             package ExprParser;
7 1     1   3 use base qw( Parser::MGC );
  1         2  
  1         452  
8              
9 1     1   5 use Feature::Compat::Try;
  1         1  
  1         4  
10              
11             # An expression is a list of terms, joined by + or - operators
12             sub parse
13             {
14 15     15   17 my $self = shift;
15              
16 15         25 my $val = $self->parse_term;
17              
18             1 while $self->any_of(
19 26     26   45 sub { $self->expect( "+" ); $self->commit; $val += $self->parse_term; 1 },
  8         21  
  8         11  
  8         61  
20 18     18   28 sub { $self->expect( "-" ); $self->commit; $val -= $self->parse_term; 1 },
  3         6  
  3         5  
  3         22  
21 15     15   44 sub { 0 },
22 15         61 );
23              
24 15         44 return $val;
25             }
26              
27             # A term is a list of factors, joined by * or - operators
28             sub parse_term
29             {
30 26     26   21 my $self = shift;
31              
32 26         32 my $val = $self->parse_factor;
33              
34             1 while $self->any_of(
35 36     36   57 sub { $self->expect( "*" ); $self->commit; $val *= $self->parse_factor; 1 },
  7         12  
  7         10  
  7         60  
36 29     29   44 sub { $self->expect( "/" ); $self->commit; $val /= $self->parse_factor; 1 },
  3         7  
  3         5  
  3         27  
37 26     26   77 sub { 0 },
38 26         153 );
39              
40 26         77 return $val;
41             }
42              
43             # A factor is either a parenthesized expression, or an integer
44             sub parse_factor
45             {
46 36     36   30 my $self = shift;
47              
48             $self->any_of(
49 36     36   54 sub { $self->committed_scope_of( "(", 'parse', ")" ) },
50 34     34   49 sub { $self->token_int },
51 36         131 );
52             }
53              
54             if( !caller ) {
55             my $parser = __PACKAGE__->new;
56              
57             while( defined( my $line = ) ) {
58             try {
59             my $ret = $parser->from_string( $line );
60             print "$ret\n";
61             }
62             catch ( $e ) {
63             print $e;
64             }
65             }
66             }
67              
68             1;