Dual-license your content for inclusion in The Perl 5 Wiki using this HOWTO, or join us for a chat on irc.freenode.net#PerlNet.
Using do for configuration
From PerlNet
The Question
On Canberra Perl Mongers the following was asked in March 2006 by Michael James:
In the perl cookbook it suggests a good way to keep local configuration details out of a larger and messier script is to put normal perl code into a separate file and "do" it.
But in a throwaway line (middle of page 328) it says, of course neither the doer nor the done will have access to the other's lexical (my) variables.
Hang ON! Lets get this clear, the done.config file can't create a variable visible to the calling program, nor see a pre-existing variable to change it.
What's the point?
Can any of you lexicographers explain a way around this, to a bear of limited scope?
The Answer
Lexical variables (declared with my) last until the end of the current block, file, or eval. When do is used to evaluate the contents of a file, neither file has access to the other's lexical variables, yet both perldoc -f do and The Perl Cookbook recommend do as one potential way to load configuration from an external file. How does this work?
The answer, thankfully, is simple. do will return the value of the last statement executed, or the result of the first return statement to be executed. Think of the entire file as being a subroutine.
This means that a file executed with do can return a value just like any other subroutine; as a list, as a scalar, or as a reference. The following provides an example:
If we have a file named configuration.pl containing:
# This simply returns a hash reference of our data.
return {
directory => "/usr/local/example",
timeout => 30,
hostname => "www.example.com",
}
Then the following will print www.example.com:
# Read our configuration as a hashref from configuration.pl
my $config = do "configuration.pl";
print "$config->{hostname}\n";
For more robust configuration, a module such as Config::General should be used.

