in reply to Re: possible to evaluate scalars stored in a string?
in thread possible to evaluate scalars stored in a string?
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)%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'});
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.
|
|---|