in reply to Check to see if a variable exists

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

Replies are listed 'Best First'.
Re: Re: Check to see if a variable exists
by jpream (Initiate) on Nov 13, 2003 at 18:54 UTC
    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