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   134984 use 5.006; use strict; use warnings;
  2     2   16  
  2     2   9  
  2         3  
  2         36  
  2         8  
  2         3  
  2         57  
2 2     2   10 use Carp ();
  2         3  
  2         407  
3              
4             package Config::INI::Tiny;
5              
6             our $VERSION = '0.104';
7              
8 27     27 1 17532 sub new { my $class = shift; bless { section0 => '', line0 => 0, pairs => 0, @_ }, $class }
  27         110  
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 32 my $self = shift;
17 27         148 my $n = $self->{'line0'}, my @out = my $s = [ $self->{'section0'} ], pos( $_[0] ) = 0;
18 2 50   2   7 BEGIN { utf8->import if eval { require utf8 } } # 5.6 compat
  2         573  
19 27         264 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       881 : defined $4 ? Carp::croak map { s/"/\\"/g; qq'Bad INI syntax at line $n: "$_"' } "$4"
  5 100       14  
  5 100       518  
    100          
23             : ()
24             }
25 22 50       91 wantarray ? @out : $out[0];
26             }
27              
28             sub to_hash {
29 26     26 1 35 my $self = shift;
30 26         43 my ( @section, %config ) = do { local $self->{'pairs'}; $self->parse( $_[0] ) };
  26         53  
  26         50  
31 21 100       65 shift @section unless @{ $section[0] } > 1; # remove initial unnamed section if empty
  21         50  
32 21         41 push @{ $config{ shift @$_ } }, $_ for @section; # collect sections in HoAoA, to minimise (re)alloc work
  35         82  
33 21         171 $_ = { map @$_, @$_ } for values %config; # flatten HoAoA to HoH as cheaply as possible
34 21         64 \%config;
35             }
36              
37             __END__