Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Divine advisors,

I am new to perl and am trying to figure out the best way to determine if a variable exists. I have a config file that may or may not have certain variables defined and I need to check to see if the variable actually exists before doing any action. Does anyone have any sample code they could share on the best approach to this??
All help and suggestions greatly appreciated.

Replies are listed 'Best First'.
Re: Check to see if a variable exists
by rinceWind (Monsignor) on Nov 13, 2003 at 17:56 UTC
    If you are new to perl, as you say you are, it's an excellent idea to get into good habits :).

    There is a recognised way of finding when your variables don't exist, and that is to insert the line

    use strict;
    at the top of your code below the #! line. This forces all variables to be predeclared before they are used, generating compile errors to catch your tired finger typos.

    On another note, you might like to try using the super search facility of the monastery, to find if similar questions have been asked before.

    rinceWind

    --
    I'm Not Just Another Perl Hacker
      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}) {}

        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

Re: Check to see if a variable exists
by bear0053 (Hermit) on Nov 13, 2003 at 17:54 UTC
    you can do the following to see if a var is defined:
    my $var_val; if(defined($var_val)){ print "defined"; } else{ print "undefined": }
    this case would pring undefined. if you had
    my $var_val = 'something';
    it would have printed: defined
Re: Check to see if a variable exists
by EdwardG (Vicar) on Nov 13, 2003 at 19:32 UTC
    On the offchance that you mean Environment variables (I'm guessing by your reference to configuration files), it might be helpful to look at Env
    NAME Env - perl module that imports environment variables as scalars or + arrays SYNOPSIS use Env; use Env qw(PATH HOME TERM); use Env qw($SHELL @LD_LIBRARY_PATH); DESCRIPTION Perl maintains environment variables in a special hash named %ENV. + For when this access method is inconvenient, the Perl module "Env" a +llows environment variables to be treated as scalar or array variable +s.
Re: Check to see if a variable exists
by ysth (Canon) on Nov 14, 2003 at 03:13 UTC
    As already mentioned in one reply, it can simplify your life to have your config file set up a hash instead, and then use exists($config_vars{foo}) to check for foo.

    If, for some reason, you can't change how the config file returns things, check if a config var foo is defined with defined($foo) which will return a true or false value.

    That just checks to see if the variable has a defined value. The literal answer to your question to check if a variable exists is to check *foo{SCALAR} which will return true (actually, a reference to the variable) if a scalar variable $foo exists. This isn't of much practical use, since code like if (*foo{SCALAR}) { print "foo is $foo"} will always do the print, since the compiler will create the variable before runtime when it sees the $foo. The other problem is that if perl sees any kind of foo variable (hash, array, sub, format, glob) it will create that kind *and* a bonus scalar $foo. So stick with defined($foo).

Re: Check to see if a variable exists
by Anonymous Monk on Sep 13, 2025 at 10:53 UTC
    one of the first maintenance tasks at megacorp was to write some code that checked to see whether a variable was mentioned anywhere else in the codebase because collisions.