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

Actually, it may not be obvious and apparent, but what you are really in need of is a closure. That is, at one point in time, you want to create a hash-value which will depend on the values which other variables have *at a later time* when you look to that value. Here's an example:
%hash = ( # the sub { ... } means that this is a closure (a subroutine refere +nce) command1 => sub { "command_name -n $var1 -p $var2" } ); $var1 = 'foo'; $var2 = 'bar'; # added "->()" because we are dereferencing a subroutine reference... +a closure system ($hash{'command1'}->());
Who loves closures? This guy.

------------
:Wq
Not an editor command: Wq

Replies are listed 'Best First'.
Re: Re: possible to evaluate scalars stored in a string? (dynamic scoping)
by etcshadow (Priest) on Dec 13, 2003 at 04:54 UTC
    Actually... I suppose, as a more direct answer to your question... you can do this:
    %hash = ( # note the single-quotes wrapping the double-quotes... # I've defined a character string which is, itself, a valid # perl expression... which can be eval'd later command1 => ' "command_name -n $var1 -p $var2" ' ); $var1 = 'foo'; $var2 = 'bar'; # this is the "later" I promised above, when we eval # the character string which contains the perl expression system (eval $hash{'command1'});
    The difference between this post and the parent post is actually only a very slight difference. This code is still, in essence, defining a subroutine reference, but it is not a closure. A closure implies static scoping, that is: the $var1 and $var2 which are visible at the time the closure is defined will be the $var1 and $var2 which are referenced at the time the code is executed. This example, however, uses dynamic scoping, that is: the $var1 and $var2 which get referenced when the code is executed are whatever variables named $var1 and $var2 are visible to the scope which executes the code. (static scoping=bound to the scope in which it was defined, dynamic scoping=scoped to wherever it is executed, whenever it is executed)

    Anyway, in this very simple example, the two are functionally equivalent, but if you imagine that the hash is defined in a different scope than the value is asked for (=code is executed), then they will behave differently. Without your full code, I couldn't say which is the right one... but the dynamicaly scoped one is closer to the title of your question at least.

    Aside: In college, I learned about dynamic lexical scoping, and thought someone would have to be on crack to use it, let alone implement it in a language. Then I met eval, and my life was forever changed.


    ------------
    :Wq
    Not an editor command: Wq