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   479 use strict;
  1         2  
  1         30  
4 1     1   5 use warnings;
  1         1  
  1         36  
5              
6             package ExprParser;
7 1     1   5 use base qw( Parser::MGC );
  1         2  
  1         617  
8              
9 1     1   7 use Feature::Compat::Try;
  1         2  
  1         4  
10              
11             # An expression is a list of terms, joined by + or - operators
12             sub parse
13             {
14 15     15   22 my $self = shift;
15              
16 15         23 my $val = $self->parse_term;
17              
18             1 while $self->any_of(
19 26     26   53 sub { $self->expect( "+" ); $self->commit; $val += $self->parse_term; 1 },
  8         23  
  8         10  
  8         67  
20 18     18   35 sub { $self->expect( "-" ); $self->commit; $val -= $self->parse_term; 1 },
  3         8  
  3         5  
  3         26  
21 15     15   52 sub { 0 },
22 15         74 );
23              
24 15         58 return $val;
25             }
26              
27             # A term is a list of factors, joined by * or - operators
28             sub parse_term
29             {
30 26     26   28 my $self = shift;
31              
32 26         41 my $val = $self->parse_factor;
33              
34             1 while $self->any_of(
35 36     36   75 sub { $self->expect( "*" ); $self->commit; $val *= $self->parse_factor; 1 },
  7         15  
  7         12  
  7         91  
36 29     29   59 sub { $self->expect( "/" ); $self->commit; $val /= $self->parse_factor; 1 },
  3         7  
  3         5  
  3         32  
37 26     26   94 sub { 0 },
38 26         177 );
39              
40 26         93 return $val;
41             }
42              
43             # A factor is either a parenthesized expression, or an integer
44             sub parse_factor
45             {
46 36     36   39 my $self = shift;
47              
48             $self->any_of(
49 36     36   71 sub { $self->committed_scope_of( "(", 'parse', ")" ) },
50 34     34   70 sub { $self->token_int },
51 36         161 );
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;