in reply to evaluating a string into the executing program

What's the bigger picture? That is: what is it that you want to use this technique to achieve? What you have at present (apart from @${arrayname} should probably be @$arrayname)

It may be that you are trying to do something like:

my @FOO; routine (); print "@FOO"; sub routine { my $arrayname = "FOO"; my $string = "\@$arrayname = ('foo', 'bar');"; eval $string; }

Prints:

foo bar

If so, don't. Almost certinally there are better ways to do it, whatever it is.


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: evaluating a string into the executing program
by deorth (Scribe) on Jul 14, 2007 at 01:00 UTC
    The bigger picture is that I have config files that are perl code. Not my choice but I'm trying to make some tools work within that system.
    I need to pluck strings from those config files, which *fortunately* do conform to the format given in my original post. Then I need to do stuff with that array of data (specifically lookup a bunch of hosts and delete any that don't resolve, but the purpose will vary with time I'm sure)
    So, I can parse it out with regex if need be, but would prefer a quick win since it really is a valid hunk of perl.
    I've tried PPI and my head hurts so I won't go there again :)
      Are you trying to execute the content of the config files? If so, a simple require "config.pl" (or whatever the config file/script is named) will do that.

      If you just need to extract specific information from the config file without executing it, then that gets a bit trickier, yeah. I can't really say how to handle that case without a sample of what one of these files looks like, which contents you want from it, and what you want to do with them.

        Well, simplistically I could do :
        open(FILE, "< $file") || die "Couldn't open $file: $!\n"; @array = <FILE>; ## Assume no multiline stuff.. for now @strings = grep(/^\s*\@$arrayname\s*=\s*/, @array);

        $string[0] then contains the piece of perl code I wish to execute. Now I thought of really hacky stuff like dropping it into a tempfile and then require'ing the file, but thats just icky. :)