added a caveat regarding XML::Simple's strict mode (Peter Corlett)
[p5sagit/Config-Any.git] / lib / Config / Any / INI.pm
1 package Config::Any::INI;
2
3 use strict;
4 use warnings;
5
6 our $MAP_SECTION_SPACE_TO_NESTED_KEY = 1;
7
8 =head1 NAME
9
10 Config::Any::INI - Load INI config files
11
12 =head1 DESCRIPTION
13
14 Loads INI files. Example:
15
16     name=TestApp
17     
18     [Controller::Foo]
19     foo=bar
20     
21     [Model::Baz]
22     qux=xyzzy
23
24 =head1 METHODS
25
26 =head2 extensions( )
27
28 return an array of valid extensions (C<ini>).
29
30 =cut
31
32 sub extensions {
33     return qw( ini );
34 }
35
36 =head2 load( $file )
37
38 Attempts to load C<$file> as an INI file.
39
40 =cut
41
42 sub load {
43     my $class = shift;
44     my $file  = shift;
45
46     require Config::Tiny;
47     my $config = Config::Tiny->read( $file );
48
49     die $Config::Tiny::errstr if not defined $config;
50
51     my $out = delete $config->{ _ } || {};
52
53     for my $k ( keys %$config ) {
54         my @keys = split /\s+/, $k;
55         my $ref = $config->{ $k };
56
57         if ( $MAP_SECTION_SPACE_TO_NESTED_KEY && @keys > 1 ) {
58             my ( $a, $b ) = @keys[ 0, 1 ];
59             $out->{ $a }->{ $b } = $ref;
60         }
61         else {
62             $out->{ $k } = { %{ $out->{ $k } || {} }, %$ref };
63         }
64     }
65
66     return $out;
67 }
68
69 =head2 is_supported( )
70
71 Returns true if L<Config::Tiny> is available.
72
73 =cut
74
75 sub is_supported {
76     eval { require Config::Tiny; };
77     return $@ ? 0 : 1;
78 }
79
80 =head1 PACKAGE VARIABLES
81
82 =over 4
83
84 =item $MAP_SECTION_SPACE_TO_NESTED_KEY (boolean)
85
86 This variable controls whether spaces in INI section headings will be expanded into nested hash keys.
87 e.g. it controls whether [Full Power] maps to $config->{'Full Power'} or $config->{'Full'}->{'Power'}
88
89 By default it is set to 1 (i.e. true). 
90
91 Set it to 0 to preserve literal spaces in section headings:
92
93     use Config::Any;
94     use Config::Any::INI;
95     $Config::Any::INI::MAP_SECTION_SPACE_TO_NESTED_KEY = 0;
96
97 =back
98
99 =head1 AUTHORS
100
101 Brian Cassidy E<lt>bricas@cpan.orgE<gt>
102
103 Joel Bernstein E<lt>rataxis@cpan.orgE<gt>
104
105 =head1 COPYRIGHT AND LICENSE
106
107 Copyright 2007 by Brian Cassidy, portions copyright 2006, 2007 by Joel Bernstein
108
109 This library is free software; you can redistribute it and/or modify
110 it under the same terms as Perl itself. 
111
112 =head1 SEE ALSO
113
114 =over 4 
115
116 =item * L<Catalyst>
117
118 =item * L<Config::Any>
119
120 =item * L<Config::Tiny>
121
122 =back
123
124 =cut
125
126 1;