File Coverage

blib/lib/Config/INI/Tiny.pm
Criterion Covered Total %
statement 32 32 100.0
branch 12 14 85.7
condition n/a
subroutine 8 8 100.0
pod 3 3 100.0
total 55 57 96.4


line stmt bran cond sub pod time code
1 2     2   138917 use 5.006; use strict; use warnings;
  2     2   16  
  2     2   15  
  2         4  
  2         49  
  2         8  
  2         6  
  2         62  
2 2     2   10 use Carp ();
  2         7  
  2         430  
3              
4             package Config::INI::Tiny;
5              
6             our $VERSION = '0.106';
7              
8 27     27 1 18063 sub new { my $class = shift; bless { section0 => '', line0 => 0, pairs => 0, @_ }, $class }
  27         126  
9              
10             my $str = '[^\r\n]* [^\r\n\t ]';
11             my $ws = '[\t ]*';
12             my $cmt = '[#;]'; # separate var because cf. "Starting in Perl 5.001" in L
13             my $rx = qr{\G $ws (?: $cmt (?:$str)? | \[ $ws ($str) $ws \] | ([^=\r\n]+?) $ws = $ws ($str|) | ($str) )? $ws (?:\z|\n|\r\n?) }x;
14              
15             sub parse {
16 27     27 1 34 my $self = shift;
17 27         100 my $n = $self->{'line0'}, my @out = my $s = [ $self->{'section0'} ], pos( $_[0] ) = 0;
18 2 50   2   11 BEGIN { utf8->import if eval { require utf8 } } # 5.6 compat
  2         693  
19 27         304 while ( ++$n, $_[0] =~ /$rx/g ) {
20             ; defined $2 ? push @$s, $self->{'pairs'} ? [ "$2", "$3" ] : ( "$2", "$3" )
21             : defined $1 ? push @out, $s = [ "$1" ]
22 106 100       832 : defined $4 ? Carp::croak map { s/"/\\"/g; qq'Bad INI syntax at line $n: "$_"' } "$4"
  5 100       15  
  5 100       527  
    100          
23             : ()
24             }
25 22 50       97 wantarray ? @out : $out[0];
26             }
27              
28             sub to_hash {
29 26     26 1 39 my $self = shift;
30 26         41 my ( @section, %config ) = do { local $self->{'pairs'}; $self->parse( $_[0] ) };
  26         66  
  26         59  
31 21 100       34 shift @section unless @{ $section[0] } > 1; # remove initial unnamed section if empty
  21         52  
32 21         48 push @{ $config{ shift @$_ } }, $_ for @section; # collect sections in HoAoA, to minimise (re)alloc work
  35         96  
33 21         135 $_ = { map @$_, @$_ } for values %config; # flatten HoAoA to HoH as cheaply as possible
34 21         69 \%config;
35             }
36              
37             __END__