Reputation: 1029
how to do this
puts [string map { ( ) "\(" "\)"} (3.8.001)]
o\p I'm getting $tclsh main.tcl
(3.8.001)
I'm expecting
\(3.8.001\)
help me to do this
Upvotes: 0
Views: 6983
Reputation: 137707
Whenever I'm confused about how exactly to write a complex string map
with backslashes involved, I try building the mapping list with list
. I might then use the literal it produces rather than having my script contain the actual list
command call, but that's purely optimisation on my part. (And a very low value one; the bytecode compiler does it for me if all the arguments to list
are literals.) In particularly tricky cases, I'll build it by stages with lappend
, but that's only where what is going on is a true head-scratcher!
Also, the mapping is supposed to be “replaceA withA replaceB withB ...
”; you were putting )
and "\("
in the wrong order, and the result would not have been expected to work at all.
set mapping [list "(" "\\(" ")" "\\)"]
# puts "mapping is “$mapping”"; # Yay for unicode quote characters!
puts [string map $mapping (3.8.001)]
The sequence you were looking for is this, with a few more braces and fewer double-quotes, but I encourage you to learn how to work this out for yourself…
puts [string map {( {\(} ) {\)}} "(3.8.001)"]
Upvotes: 1
Reputation: 16438
You should use the string map
as follows,
puts [string map { ( "\\(" ) "\\)"} (3.8.001)]
Backslash has to be used twice, to have a single backslash when used inside double quotes in Tcl.
Upvotes: 4