Tcl split list elements in the list

I am trying to split some list elements in the list.

I want to make lists from:

beforelist: {{aa, bb, cc, dd, ee;} {ff, gg, hh, ii, jj;}}


afterlist: {aa bb cc dd ee ff gg hh ii jj}

I tried to deal with them by using split command, but beforelist has some tricky point: comma, semicolon.

3 answers

  • answered 2021-10-24 18:29 Shawn

    A couple of ways:

    #!/usr/bin/env tclsh
    set beforelist {{aa, bb, cc, dd, ee;} {ff, gg, hh, ii, jj;}}
    # Iterate over each element of each list in beforelist and remove
    # trailing commas and semicolons before appending to afterlist
    set afterlist {}
    foreach sublist $beforelist {
        foreach elem $sublist {
            lappend afterlist [regsub {[,;]$} $elem ""]
    puts "{$afterlist}"
    # Remove all commas and semicolons at the end of a word followed by space
    # or close brace, then append sublists to afterlist.
    set afterlist {}
    foreach sublist [regsub -all {\M[,;](?=[ \}])} $beforelist ""] {
        lappend afterlist {*}$sublist
    puts "{$afterlist}"

  • answered 2021-10-24 22:40 mrcalvin

    This is not necessarily a problem to be tackled using lists. Keep it a string manipulation:

    % set beforeList {{aa, bb, cc, dd, ee;} {ff, gg, hh, ii, jj;}}
    {aa, bb, cc, dd, ee;} {ff, gg, hh, ii, jj;}
    % string map {\{ "" \} "" \; "" , ""} $beforeList
    aa bb cc dd ee ff gg hh ii jj

  • answered 2021-10-25 00:47 glenn jackman

    If we remove the punctuation, we're left with 2 lists that can be concatenated

    set afterlist [concat {*}[string map {, "" ; ""} $beforelist]]

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum