Returns a value equal to string except that any leading characters from the set given by chars are removed. If chars is not specified then white space is removed (spaces, tabs, newlines, and carriage returns).
WJP In my experience perhaps the most common use of 'string trimleft' with non-default arguments, that is, to trim something other than whitespace, is stripping of leading zeroes so that tcl will not mistakenly think that a number is octal. The usual usage ( [string trimleft $foo 0]) however leads to a subtle and typically sporadic bug: if the argument is "0", the result of trimming the leading zero is to eliminate the string entirely. The error messages that this generates are not very helpful - typically you'll get something like "not enough arguments".
Lars H, 19 Sep 2005: That sounds to me as though you also have insufficient quoting, e.g. not bracing exprs, or not using list for things fed through eval. The following demonstrates the difference this can make for the error messages:
% set a "" % expr {2+$a} Error: can't use empty string as operand of "+" % expr 2+$a Error: syntax error in expression "2+": premature end of expression
WJP (continued): Here's a little procedure that does the right thing:
proc TrimLeadingZeroes {n} { if {[string length $n] == 0} {return ""} set trimmed [string trimleft $n 0] if {[string length $trimmed] == 0} { return "0" } else { return $trimmed } }
I suggest always using such a procedure. Not only does it avoid forgetting to handle this case, but it avoids breaking the functional programming style.
ramsan: Alternatively, you can also use:
set n [scan $n %d]
Lars H: Or, for capturing the error condition:
if {[ scan $n %d n; # Written on a separate line, for emphasis. }] != 1} then { error "Expected integer, but got: $n" }
If no error capturing is wanted, then
scan $n %d n
will do as well.