in reply to Re: Check to see if a variable exists
in thread Check to see if a variable exists

One way I have done config files is to setup the config file as a do'able variable in itself that is a reference to a hash.. You can also use Data::Dumper to create the file. config.txt file as such:
$config = \{ 'Variable1' => 'variable value', 'Variable2' => ['a','b','c'], };
Then you can:
do "config.txt" or die "$! $@";
This creates a variable $config that is a reference to a hash containing all your configuration variables. If your passing the configuration to subroutines you can just pass $config and your subroutine has access to all the config variables and you saved some overhead.

Granted you have to dereference the hash, but references are a good thing to learn..

if (exists $config->{Variable1}) {}

Replies are listed 'Best First'.
Re: Re: Re: Check to see if a variable exists
by hardburn (Abbot) on Nov 13, 2003 at 20:08 UTC

    Even better is to put your config in a module, with each configuration option being a subroutine declared with an empty prototype (and thus considered by the compiler for inlineing). Example:

    package My::Config; sub VARIABLE1 () { 'variable value' } sub VARIABLE2 () { [ 'a', 'b', 'c' ] } 1;

    You call it like this:

    use My::Config; my $var1 = My::Config::VARIABLE1;

    Which, if you put this through B::Deparse, will look like:

    use My::Config; # Actually, my $var = 'variable value';

    And is thus gives you the advantages of a hard-coded variable without the icky problem of maintainability.

    Note, though, that strict won't catch undeclared variables with full package names, so if you do:

    my $var1 = My::Config::VAR1;

    strict will happily allow it.

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    : () { :|:& };:

    Note: All code is untested, unless otherwise stated