use Config::File;
$conf = Config::File->new( file => $file, path => $path );
print $conf->key;
####
use Config::File 'config';
%hash = config( file => $file, path => $path );
print $hash{key};
##
##
use Config::File 'config';
$hashref = config( file => $file, path => $path );
print $hashref->{key};
##
##
use Config::File;
$conf = Config::File->new(file => 'my.conf');
print $conf->db_password, $/;
print $conf->blocked_words->[0], $/;
print $conf->emails->{webmaster}, $/;
##
##
{
db_password => 'secret',
blocked_words => ['list', 'of', 'words'],
emails => { sales => 'sales@fireartist.com',
webmaster => 'webmaster@fireartist.com',
}
}
##
##
secret
list
webmaster@fireartist.com
##
##
package Config::File;
$VERSION = '0.30';
use strict;
require Exporter;
use vars qw($VERSION @ISA @EXPORT_OK $AUTOLOAD);
@ISA = qw(Exporter);
@EXPORT_OK = qw/config/;
use Carp;
use File::Spec;
sub new {
my $class = shift;
my %arg = @_;
my $self = {};
bless( $self, $class );
my $file = _file_path( $arg{file}, $arg{path} );
$self->{conf} = do($file)
or croak('new() could not load config file');
return $self;
}
sub config {
my $self = shift if ref $_[0];
my %arg = @_;
my $file = _file_path( $arg{file}, $arg{path} );
my $conf = do($file)
or croak('hash() could not load config file');
return (wantarray ? %{ $conf } : $conf);
}
sub _file_path {
my ($file, $path) = @_;
my $exists;
croak('_file_path requires file arg') unless defined $file;
if ($path && -e File::Spec->catfile( $path, $file )) {
$exists = File::Spec->catfile( $path, $file );
}
elsif ( -e $file ) {
$exists = $file;
}
else {
for (@INC) {
if (-e File::Spec->catfile( $_, $file )) {
$exists = File::Spec->catfile( $_, $file );
last;
}
}
}
croak('could not find config file') unless defined $exists;
return $exists;
}
sub AUTOLOAD {
my $self = shift;
my $method = $AUTOLOAD;
$method =~ s/.*://;
unless (defined $self->{conf}->{$method}) {
croak($method.' not defined in config file');
}
return $self->{conf}->{$method} if not wantarray;
if (ref $self->{conf}->{$method} eq 'HASH') {
return %{ $self->{conf}->{$method} };
}
elsif (ref $self->{conf}->{$method} eq 'ARRAY') {
return @{ $self->{conf}->{$method} };
}
else {
return $self->{conf}->{$method};
}
}
sub DESTROY { }
1;