Search code examples
listautomationscriptingtclexpect

Expect script create list and append to it


I'm currently trying to create a list into an expect script and to fill it later

I can declare and initialize the list as follow

#!/usr/bin/expect

set matchList [list test1 test2]

foreach elem $matchList {
    puts $elem
}

Which gives the following result

$ ./tmp.expect 
test1
test2

However I can't find a way to correctly append a new string to the list

I have tried several syntax without being able to find the proper way

  • set matchList [list $matchList test3]

Considers that 'test1 test2' is the first element and 'test3' the second

$ ./tmp.expect 
test1 test2
test3
  • set matchList [list [foreach elem $matchList { puts $elem } ] test3]

Set the third element as an empty string and 'test3' is the fourth element

$ ./tmp.expect 
test1
test2

test3
  • set matchList [list [foreach elem $matchList { puts $elem } ]test3]

By removing the space after the foreach block The list is correctly filled. However it seems a bit overkill to do such a simple task.

$ ./tmp.expect 
test1
test2
test3

Does anybody knows how to correctly fill a list element by element into an expect script ?


Solution

  • The proper way to add an element to the end of a list in Tcl is to use lappend; the first argument is the name of a variable containing a list, and the second and subsequent arguments are values to append:

    lappend matchList test3
    

    That works even when values have metacharacters embedded within them.