0

Suppose I have a string which is also a Tcl command.

set line {lsort -unique [list a b c a]}

How can I convert this string into a list equivalent to this?

  {
      {lsort}
      {-unique}
      {[list a b c a]}
  }

Because of whitespace inside the square brackets, I can't just use lindex. For example:

> lindex $line 2
   -->  [list

The reason I'm asking is because I have a large Tcl script that I want to parse and re-write. I would like certain lines in the re-written script to have swapped argument order or some numerical arguments scaled by a factor.

I know I could parse the string character by character, keeping track of {}, [], and " characters, but this feels like re-inventing something that might already exist. I've been looking at the info and interp commands but couldn't find anything there.

3
  • info complete - tcl.tk/man/tcl/TclCmd/info.html#M10 - is likely to be useful here. You could work through the string, breaking it at each point where info complete returns true. Nov 1, 2022 at 14:02
  • Yes, I was considering info complete but wanted to ask for alternatives first. Nov 1, 2022 at 14:23
  • info complete only answers "is this a complete command that I could throw into the Tcl interpreter?" but not what the words in that command are. Sounds like you might be more interested in wiki.tcl-lang.org/page/tclparser Nov 1, 2022 at 15:45

1 Answer 1

1

I used info complete successfully in this proc.

proc command_to_list {command} {
    # split by whitespace
    set words  [regexp -all -inline {\S+} $command]
    set spaces [regexp -all -inline {\s+} $command]

    set output_list [list]
    set buffer ""

    foreach word $words space $spaces {
        append buffer $word 

        if {[info complete $buffer]} {
            lappend output_list $buffer
            set buffer ""
        } else {
            append buffer $space 
        }
    }
    return $output_list
}

This proc will group whitespace separated 'words' until they have no unmatched curlies, double quotes, or square brackets. Whitespace is preserved inside of matching pairs of curlies, double quotes or square brackets.

> set command {foreach {k v} [list k1 v1 k2 v2] {puts "$k    $v"}}
> foreach word [command_to_list $command] {puts $word}
foreach
{k v}
[list k1 v1 k2 v2]
{puts "$k    $v"}
1
  • Perhaps you can't do without reinventing something, as there might be multiple line commands continued by \ and strings continued in multiple lines even without \. To say nothing about commands receiving procedure/method bodies. But in your case it may be not critical, depending on the problem set before you.
    – Alex P
    Nov 11, 2022 at 3:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.