Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Re: possible to evaluate scalars stored in a string?

by emilford (Friar)
on Dec 13, 2003 at 03:50 UTC ( [id://314467]=note: print w/replies, xml ) Need Help??


in reply to Re: possible to evaluate scalars stored in a string?
in thread possible to evaluate scalars stored in a string?

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

Replies are listed 'Best First'.
Re: Re: Re: possible to evaluate scalars stored in a string?
by tachyon (Chancellor) on Dec 13, 2003 at 04:17 UTC

    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

        ++ I remebered there was a double quoting way to do it but could not remeber exactly what and make it work.....

        cheers

        tachyon

Re: Re: Re: possible to evaluate scalars stored in a string?
by Mr. Muskrat (Canon) on Dec 13, 2003 at 04:04 UTC
    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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://314467]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2024-04-24 19:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found