Why use Perl::Critic if you don't want to follow its advice?
Using require to load a configuration file is a bad idea. For one thing it will silently fail to load the file into more than one package. From the docs for require:
Otherwise, require demands that a library file be included if it hasn't already been included. ... Note that the file will not be included twice under the same specified name.
$ cat conf.pl
#!/usr/bin/perl
use strict;
use warnings;
our %conf = (
foo => 'bar',
baz => 'quux'
);
__END__
$ cat ONE.pm
package ONE;
use strict; use warnings;
sub one {
our %conf;
require 'conf.pl';
return $conf{'foo'};
}
1;
$ cat TWO.pm
package TWO;
use strict; use warnings;
sub two {
our %conf;
require 'conf.pl';
return $conf{'baz'};
}
1;
$ cat 1137798.pl
#!/usr/bin/perl -w
use strict;
use ONE;
use TWO;
print ONE::one, "\n";
print TWO::two, "\n";
__END__
Output:
$ perl 1137798.pl
bar
Use of uninitialized value in print at 1137798.pl line 8.
Change the require calls to do as somebody else noted and you can then import your config file into more than one package, which is useful.
$ cat ONE.pm
package ONE;
use strict; use warnings;
sub one {
our %conf;
#require 'conf.pl';
do 'conf.pl';
return $conf{'foo'};
}
1;
$ cat TWO.pm
package TWO;
use strict; use warnings;
sub two {
our %conf;
#require 'conf.pl';
do 'conf.pl';
return $conf{'baz'};
}
1;
$ perl 1137798.pl
bar
quux
So use do, or better yet, just use Config::Tiny, which exists to solve your problem.
$ cat conf.ini
[path]
foo=bar
some=other
[url]
baz=quux
less=more
$ cat 1137798-2.pl
#!/usr/bin/perl -w
use strict;
use Config::Tiny;
my $conf = Config::Tiny->read( 'conf.ini' );
print $conf->{path}->{foo}, "\n";
print $conf->{url}->{baz}, "\n";
__END__
Output:
$ perl 1137798-2.pl
bar
quux
Now what's overkill about that?
The way forward always starts with a minimal test.
|