Search code examples
tcl

Tcl string range behavior


A small routine places a five character marker within an output file every several thousand bytes, that marker containing numbers that usually are > 10000, but may contain as few as one digit. The marker must contain five characters, and are thus left side padded with zeros. Since the length of the marker is unknown at the beginning of each iteration, four zeroes are padded and then some or all are dropped.

Assume that x represents the actual marker and that x = 400

If I:

set x 0000$x
set x [string range $x [expr [string length $x] - 5] end]

the script will return "00400", which is what we need. However, if I shorten it to:

set x [string range $x [expr [string length "0000$x"] - 5] end]

it will return "0". I hope someone can point out where I'm going wrong.


Solution

  • In your second example, you are computing the length of one string (0000400) and then taking the characters from another (400).

    % string length 0000400
    7
    % string range 400 2 end
    0
    

    You'd be better to use format or end-relative indexing:

    string range "0000$x" end-4 end
    
    format "%05d" $x