I’m trying to solve the Roman Numerals exercise, and so far I’m going pretty well, but I don’t really understand how does the map work. I tried doing this at the end:
string map {CCCCCCCCC CM CCCCC D CCCC CD XXXXXXXXX XC XXXXX L XXXX XL IIIIIIIII IX IIIII V IIII IV} $result
But it doesn’t work at all, and separatedly, while the map to CM works, the rest don’t seem to. How does it exactly work?
Basically, it walks the given string character-by-character, trying to match one of the “key” strings. If one is found, the replacement is made, and the walk continues at the next character.
$ tclsh
% set result MMMCCCCCCCCCXXXXXXXXXIIIIIIIII
MMMCCCCCCCCCXXXXXXXXXIIIIIIIII
% string map {CCCCCCCCC CM CCCCC D CCCC CD XXXXXXXXX XC XXXXX L XXXX XL IIIIIIIII IX IIIII V IIII IV} $result
MMMCMXCIX
Ah, string mapreturns a value, it does not replace a value.
In Tcl, $varname is the contents of the variable. Once the parser substitutes the variable content, the command (“string map” in this case) cannot know anything about which variable provided the value.
The manual pages try to be explicit about it. For example append