in reply to possible to evaluate scalars stored in a string?

I think that you have answered your question for yourself. What do I mean by that?

"Some of the parameters are stored elsewhere in the script as scalars and would need to be evaluated at the time of use."

That's what eval is for! It evaluates things at run time. I'm thinking the last line should be: system(eval{$hash{command1}});

But I did not test it, YMMV, objects in mirror may be closer than they appear, any bit rot caused by using this is to be blamed upon alpha particles and not me.

Updated the code snippet (eval needed braces and not parentheses). I did test it, but as always: YMMV, objects in mirror may be closer than they appear, any bit rot caused by using this is to be blamed upon alpha particles and not me.

Replies are listed 'Best First'.
Re: Re: possible to evaluate scalars stored in a string?
by emilford (Friar) on Dec 13, 2003 at 03:50 UTC
    I still don't think this works. Here's what I have:
    %alerts = ('command1' => 'Command1 = $val1'); $val1 = 'foobar'; print "eval {$alerts{command1}}";
    This prints out "Command1 = ".

      What you need is eval, BUT 'command $foo' is unlikely to be valid perl so the eval will fail. This regex method works because we capture the scalar and perform the required (double) eval (first eval gets you $var out of $1, second gets you 'value' out of $var). You may wish to add more than \w in the capture after the $ for things like $foo->{bar} if you are getting that weird.

      %hash = ( 'command' => 'command_name -n $var1 -p $var2' ); $var1 = 'foo'; $var2 = 'bar'; $command = $hash{'command'}; $command =~ s/(\$\w+)/$1/gee; print $command; # system ($command); __DATA__ command_name -n foo -p bar
      This is almost certainly a bad way to do it BTW.

      cheers

      tachyon

        Well, it's perfectly possible and reasonable to do it with eval:
        %hash = ( 'command' => '"command_name -n $var1 -p $var2"' ); $var1 = 'foo'; $var2 = 'bar'; $command = eval $hash{'command'}; print $command;
        Just changed it so that what's being eval'd is a valid perl expression that evaluates to what he wants.

        ------------
        :Wq
        Not an editor command: Wq
      Now I'm not even sure how I got it working because I didn't keep my snippet. Oh, well. I really like pg's update that uses sprintf.