在TCL中将含变量的字符串不求值传递给proc的技术问询
Great question! When you need to keep variable references like $intf intact in a string passed to a proc—avoiding both backslash escapes (\$) and curly brace wrapping—here are a few practical, compliant solutions:
1. Use a Helper Variable for the Dollar Sign
You can store the dollar character in a separate variable, then interpolate that variable to build your target string. This lets you include the $ without escaping it directly:
set intf "blah" set dollar "$" ;# Store the dollar sign as a plain variable set cmd "show router interface ${dollar}intf" dummy_proc $cmd
When you run this, $cmd will hold exactly "show router interface $intf" because ${dollar} is replaced with $, and the following intf is treated as plain text (not a variable reference) in the interpolation.
2. Use string map to Insert Variable References
Construct a template string with a placeholder, then replace that placeholder with the unevaluated variable reference using string map:
set intf "blah" set cmd_template "show router interface @intf_placeholder" set cmd [string map {@intf_placeholder {$intf}} $cmd_template] dummy_proc $cmd
This approach keeps your template clean, and string map inserts the literal $intf into the string without triggering variable substitution during the initial assignment.
3. Build the String Incrementally with append
You can build the string piece by piece using append, which treats all inputs as plain text (no interpolation happens during the append operation itself):
set intf "blah" set cmd "show router interface " set dollar "$" append cmd $dollar ;# Add the dollar sign append cmd "intf" ;# Add the variable name dummy_proc $cmd
By breaking the string into parts, you avoid any accidental variable substitution while constructing the final string.
All these methods ensure that dummy_proc receives the exact string "show router interface $intf" instead of the substituted version with "blah".
内容的提问来源于stack exchange,提问作者user3624379

