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

Hi Monks,

I am trying to check the existence of variables that are listed in a string e.g:

$var2 = 1; # may just be $var $one = '$var'; $two = '$var2'; if(defined(the variable listed in $one)){ print "I don't want to see this\n" }; if(defined(the variable listed in $two)){ print "I want to see this" };
So I have a variable in existence, it may or may not have a value. I also have two strings with the name of variables in. I'd like to check to see if these variables exist but I just can't get the syntax right.

The strings are in the above format and I could change them, I could also use hashes, but I am wondering if there is a oneline that would just sort it out for me.

Cheers!

Replies are listed 'Best First'.
Re: Using a sting with a variable name
by ikegami (Patriarch) on May 11, 2009 at 14:42 UTC
      Yes, I know it is silly. Can you do it or is this just a massive conspiracy because no one can actually do it? :-)

        Yes and no.

        It's not possible to get a reliable answer for scalar package variables, but you can get a close enough answer. (If pkg var @foo exists, so does $foo even if it's never used.)

        It's not possible with lexical variables unless you're ok with actually executing the literal (and thus arbitrary code) to find out.

        There are template systems that use the syntax of Perl's interpolating literals.

        I agree this is a bad idea, but this should work:
        #!/usr/local/bin/perl -w use strict; my $var2 = 1; # may just be $var my $one = '$var'; my $two = '$var2'; if(eval("$one")){ print "I don't want to see this\n" } if(eval("$two")){ print "I want to see this\n" }
Re: Using a sting with a variable name
by JavaFan (Canon) on May 11, 2009 at 14:59 UTC
    no strict 'refs'; if (defined ${"${\substr $one, 1}"}) { ... }
    That's assuming $one contains the name of a package variable.
      if (defined ${"${\substr $one, 1}"}) {

      Instead of ${"${\substr $one, 1}"} you could also just write ${substr $one, 1}.

      It also assumes $one$var is defined if it exists. I don't know if that's ok or not.
        I was assuming from the phrasing of the question and the example that it can be given that $one is defined. Otherwise, it's a trivial test to add.