Re: Parse a Tcl variable name inside a string



On 31 oct, 14:39, Bryan Oakley <oak...@xxxxxxxxxxxxxxxxxxxx> wrote:
pma...@xxxxxxxxx wrote:
Hi,
I would like to parse variable names from a string.
Let's assume I have the following variable set
set myvar {text_$var1_text_$var2}

The $var1 and $var2 must not be replaced immediately by their values.
Now if I do the following
set var1 12
set var2 25
puts [subst $myvar]

I get "text_12_text_25", this is what I expect.

Are you aware that for the example above, you do *not* get what you
expect? You gave us a bogus example. I think we can get your meaning,
assuming you don't actually expect that specific example to work. (it
won't work because tcl doesn't know you mean $var1 rather than $var1_text_)

Sometimes, var1 might not be set before the "subst $myvar" command,
leading to a crash.
I would like to parse the variable myvar before trying to subst it, in
order to find out that it requires the variables var1 and var2 to be
defined, and then check var1 and var2.
Now, my problems : the names "var1" and "var2" can change, and even
the number of sub-variables.
Moreover, the syntax $var or ${var} might be used.

The Tcl man page gives explicit rules for doing $ substitution. You can
use those same rules to create a regular expression to pull out all the
variable definitions.

Off the top of my head, something like this might work in probably 99%
of the time for scalers:

# This should all be one line, but it likely will get
# mangled between me writing it and you reading it
regexp -all -inline \
{\${[a-zA-Z0-9_:]+(?:\([^\)]*\))?}|\$[a-zA-Z0-9_:]+(?:\([^\)]*\))?} \
$myvar

Or, just do the subst inside a catch; if there's a missing variable it
will tell you, and you can parse the name out of the error message. Of
course, this will only tell you about the first variable, but you can
write a loop that temporarily satisfies a missing variable, does the
subst again, lather, rinse, repeat until no errors are found.

--
Bryan Oakleyhttp://www.tclscripting.com

whoops, sorry for the bug, I meant ${var1} !

Many thanks to you both for your useful and quick help !
Philippe

.



Relevant Pages