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

Oh Perl Monks,
This is probably a very lame question, but I'm having trouble visualizing how to make it happen.
Say I have this :
sub routine { my $arrayname = "FOO"; my $string = "@${arrayname} = ('foo', 'bar');"; }

and I wish to make @${arrayname} accessible as actual code locally-scoped within routine, what is the eval magic to get there ?
Thanks

Replies are listed 'Best First'.
Re: evaluating a string into the executing program
by Joost (Canon) on Jul 14, 2007 at 00:24 UTC
Re: evaluating a string into the executing program
by GrandFather (Saint) on Jul 14, 2007 at 00:38 UTC

    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
      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.