Radostina Gencheva
Radostina Gencheva

Reputation: 1

Split string repeat Tcl

I am a fresh learner of Tcl and I faced an issue of understanding this whole concept:

<name of variable> set [split "[string repeat "-,-," [columns]]-",]

columns is a variable with value 6; How the split will be and which is my whole string?

Thank you all

Upvotes: 0

Views: 419

Answers (1)

glenn jackman
glenn jackman

Reputation: 246807

<name of variable> set [split "[string repeat "-,-," [columns]]-",]

You have to unpack Tcl commands from the inside out because the inner-most nested brackets are executed first.

  • columns is a proc that, hopefully, returns an integer.
  • then string repeat repeats "-,-," that many times.
  • then the double quoted string adds a trailing -
  • then split should split that "-,-,-,...-" string on commas resulting in *a list of "2 * columns + 1" hyphens*.

Except:

  • there is a missing space before the last comma in the split command
  • the set command looks like: set varname value (unless you're dealing with an object)
set <name of variable> [split "[string repeat "-,-," [columns]]-" ,]
# ...............................................................^

Demonstrating:

set columns 6
proc columns {} {return $::columns}
set result [split "[string repeat "-,-," [columns]]-" ,]
puts $result
puts [llength $result] ;# should be 13
- - - - - - - - - - - - -
13

You could achieve the same result with:

set result [lrepeat [expr {2 * [columns] + 1}] "-"]

Tcl is actually a very simple language. The entire syntax only has 12 rules: https://www.tcl.tk/man/tcl8.6/TclCmd/Tcl.htm

Upvotes: 1

Related Questions