File Coverage

examples/parse-jsonlike.pl
Criterion Covered Total %
statement 29 31 93.5
branch n/a
condition n/a
subroutine 11 12 91.6
pod n/a
total 40 43 93.0


line stmt bran cond sub pod time code
1             #!/usr/bin/perl
2              
3 1     1   553 use strict;
  1         2  
  1         34  
4 1     1   6 use warnings;
  1         2  
  1         50  
5              
6             # DO NOT RELY ON THIS AS A REAL JSON PARSER
7              
8             # It is not intended to be used actually as a JSON parser, simply to stand as
9             # an example of how you might use Parser::MGC to parse a JSON-like syntax
10              
11             # It doesn't handle things like floats, booleans or quoting of dict keys
12              
13             package JsonlikeParser;
14 1     1   6 use base qw( Parser::MGC );
  1         1  
  1         588  
15              
16 1     1   8 use Feature::Compat::Try;
  1         2  
  1         10  
17              
18             sub parse
19             {
20 20     20   28 my $self = shift;
21              
22             $self->any_of(
23             'token_int',
24             'token_string',
25              
26 7     7   23 sub { $self->committed_scope_of( "[", 'parse_list', "]" ) },
27              
28 3     3   9 sub { $self->committed_scope_of( "{", 'parse_dict', "}" ) },
29              
30 0     0   0 sub { $self->commit; $self->fail( "Expected integer, string, list, or dictionary" ) },
  0         0  
31 20         167 );
32             }
33              
34             sub parse_list
35             {
36 4     4   5 my $self = shift;
37              
38 4         15 return $self->list_of( ",", 'parse' );
39             }
40              
41             sub parse_dict
42             {
43 3     3   4 my $self = shift;
44              
45 3         4 my %ret;
46             $self->list_of( ",", sub {
47 5     5   18 my $key = $self->token_ident;
48              
49 5         14 $self->expect( ":" );
50 5         11 $self->commit;
51              
52 5         10 $ret{$key} = $self->parse;
53 3         18 } );
54              
55 3         13 return \%ret
56             }
57              
58 1     1   1235 use Data::Dumper;
  1         7532  
  1         223  
59              
60             if( !caller ) {
61             my $parser = __PACKAGE__->new;
62              
63             while( defined( my $line = ) ) {
64             try {
65             my $ret = $parser->from_string( $line );
66             print Dumper( $ret );
67             }
68             catch ( $e ) {
69             print $e;
70             }
71             }
72             }
73              
74             1;