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

Hi Monks,
basic question. I am trying to read a list of variables and then check to see if they are defined. E.g.
my $test = "\$help"; my $help = 1; if(defined($$test)){ print "defined\n"; };
Where $test is the read variable name and $help is the potentially defined/undefined variable.
I've tried a whole tonne of syntax but I can't get it to work.
Any help greatly appreciated, it's been a slow day :-)

Replies are listed 'Best First'.
Re: Dereferencing simple variable
by lakshmananindia (Chaplain) on Apr 01, 2009 at 12:43 UTC

    The following works for me

    my $help; my $test = \$help; $help = 1; if(defined($$test)){ print "defined\n"; };
    --Lakshmanan G.

    The great pleasure in my life is doing what people say you cannot do.


Re: Dereferencing simple variable
by akho (Hermit) on Apr 01, 2009 at 13:45 UTC
    It looks like you are trying to use variable names stored in strings? This is not a very good thing to do, and you should probably reconsider.

    However if you insist on doing that, you should look into symbolic references (see perlref). They only work with package variables, however (not those created with my). This seems to work:

    my $test = "help"; our $help = 1; no strict 'refs'; if(defined($$test)){ print "defined\n"; };
      I'm going to try and reconsider. As above, hashes are most proably the way forward!
Re: Dereferencing simple variable
by targetsmart (Curate) on Apr 01, 2009 at 12:43 UTC
    just defined($help) will suffice
    why you reference a scalar $help to $test, any reasons for that?.

    Vivek
    -- In accordance with the prarabdha of each, the One whose function it is to ordain makes each to act. What will not happen will never happen, whatever effort one may put forth. And what will happen will not fail to happen, however much one may seek to prevent it. This is certain. The part of wisdom therefore is to stay quiet.
      I'm reading in a large list of varibles. If the variable doesn't exist then define it. In a nutshell :-)
        That sounds like you could use a hash instead. Is there a good reason why that's not possible?
        putting the part of actual code you were talking about here will help in guiding you, also see perldsc

        Vivek
        -- In accordance with the prarabdha of each, the One whose function it is to ordain makes each to act. What will not happen will never happen, whatever effort one may put forth. And what will happen will not fail to happen, however much one may seek to prevent it. This is certain. The part of wisdom therefore is to stay quiet.
Re: Dereferencing simple variable
by planetscape (Chancellor) on Apr 02, 2009 at 10:53 UTC