Skip to content
Tcl Source Code View Ticket
Login

View Ticket

string map not correctly mapping

Closed / Invalid623448ffffffffffffffffffffffffffffffffffCreated 24 years agoUpdated 24 years ago
Descriptionplain2002-10-15 09:02:40
The following code-snippet shows the misbehaviour:
Some empty p and an "answer"-block should be added 
to this xml:

set data 
{<cnt><quest><p>q1</p></quest><ans><p>a1</p></an
s></cnt>}

# simply with map in "question" and "answer" empty "p" 
are added
# and a new "answer"-block should be inserted
set result [string map {
</p></quest> </p><p></p></quest> 
</p></ans> </p><p></p></ans>
</ans></cnt> 
</ans><ans><p></p></ans></cnt>
} $data]

# result is:
# 
<cnt><quest><p>q1</p><p></p></quest><ans><p>a1<
/p><p></p></ans></cnt>
# the empty "p" tags are inserted, but the last map-
pattern is not.

# When doing the same in two steps as here:
set result [string map {
</p></quest> </p><p></p></quest> 
</p></ans> </p><p></p></ans>
} $data]
set result [string map {
</ans></cnt> 
</ans><ans><p></p></ans></cnt>
} $result]
# now everything is fine, result is:
<cnt><quest><p>q1</p><p></p></quest><ans><p>a1<
/p><p></p></ans><ans><p></p></ans></cnt>

This is observed also in Tcl 8.2. As I see in tclCmdMZ.c 
in function Tcl_StringObjCmd the pointers of the 
matches are precomputed, may that be the problem? I 
don't really understand the rest of the code enough to 
provide a patch.
dkfplain2002-10-15 17:21:51
Logged In: YES 
user_id=79902

You seem to have misunderstood how [string map] works, and
its key feature is that it never processes the same
character twice.  This means that after the application of
the second matching pattern (though you should understand
that the order of patterns does not matter in your case) the
third pattern cannot match because to do so, it would need
to match against a mixture of input pattern and generated
text.

If you are processing XML, try using TclXSLT or TclDOM.
svogelplain2002-10-15 18:02:33
Logged In: YES 
user_id=250752

O.k. I see. This is somehow difficult to understand. The doc 
says: "string is only iterated over once, so earlier key 
replacements will have no affect for later key matches"
But it has then in some degree an effect on later key 
matches. Maybe I just misunderstood that. Now it's clear to 
me.
The example in the docs is quite good.
Thanks Donal
Log in (anonymous is fine) to add a comment.