it_says_BALLS_on_your forehead said:
hey Paul, another way i do it is to create a simple perl script:
# config.pl
sub getConfig {
my %hash = (
name1 => "val1",
name2 => "val2",
);
return %hash;
}
1;
...then, in the main script:
require "config.pl";
my %config = getConfig();
...
is there a drawback of doing it this way versus doing it your way? or
are they essentially the same? i know that "use" is generally better
than "require"--compile time versus run-time.
I can think of one disadvantage off the top of my head. In your
example, there is no package statement. Therefore, the first time this
file is "required", the code within it is loaded into the current
package. require() maintains a list of all files it has previously
loaded, and does not load them again.
Therefore, say you are working with a main file and a module. Each of
the main file and the module file "require" this config.pl. The first
time this file is required, getConfig() becomes a member of whatever
package first required the file. The second require is ignored. Now
both the mainfile and the module attempt to call getConfig(). Only one
call will succeed, because getConfig() is in only one of the correct
packages.
Perhaps an illustration would be helpful:
main.pl:
#!/usr/bin/perl
use strict;
use warnings;
use Foo;
require "config.pl";
my %cfg = getConfig();
__END__
Foo.pm:
package Foo;
use strict;
use warnings;
require "config.pl";
my %cfg = getConfig();
1;
In this example, Foo.pm's require() is executed first (as it was loaded
at compile time via the use statement). Therefore, config.pl got
brought into the package Foo. Foo.pm's call to getConfig() will
therefore succeed. Now the remainder of main.pl is parsed. It too
calls require, but this call is ignored, as the file has already been
required. When main.pl attempts to call getConfig(), it will print the
error: Undefined subroutine &main::getConfig called at main.pl line 7.
That's because main::getConfig doesn't exist - Foo::getConfig does.
The main script - and any other modules that also want to use this
function - would have to know into which package the file was first
required.
The Exporter method I used allows every file and module to import the
included subroutine into its own call space, thus avoiding this issue
entirely.
.... That turned out to be a longer post than I intended. Apologies.
Paul Lalli