Question

What should do this code sample?

set l { A B C D }
lreplace $l 1 2 \[ \]

It returns {A {[} \] D}, however I want to have {A [ ] D}.

What am I doing wrong?

Was it helpful?

Solution

Your code does exactly what you want it to, you're just reading the string rep of your output and misunderstanding it:

% set l { A B C D }
 A B C D 
% foreach elem $l { puts $elem }
A
B
C
D
% set j [lreplace $l 1 2 \[ \]]
A {[} \] D
% foreach elem $j { puts $elem }
A
[
]
D
% join $j
A [ ] D

When you read the string rep, you're seeing it escape the [ and ]. As you can see from the foreach output, the actual values are what you're asking for. You can use join to get the string you're interested in if what you want is just a string with the characters in question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top