Search code examples
for-loopexpect

Expect Script - For Loop - How to use more than 1 variable


How can I use more than 1 variable in expect script "for loop"? Please help. Thanks in advance.

With one variable:

for {set i 1} {$i < 256} {incr i 1} {

}

How can 2 or 3 variables, say init , condition, increment of i, j, k ? comma, semicolon is not working.

Thanks, Krishna


Solution

  • Keep in mind that expect is an extension of Tcl. Documentation of Tcl is available.

    The syntax of for is:

    for start test next body

    "start" and "next" are both evaluated as scripts. "test" is an expression

    You can do:

    for {set i 1; set j 10; set k "x"} {$i < 5 && $j > 0} {incr i; incr j -2; append k x} {
        puts "$i\t$j\t$k"
    }
    

    outputs

    1   10  x
    2   8   xx
    3   6   xxx
    4   4   xxxx
    

    This is equivalent to the following, so use whatever is most readable.

    set i 1
    set j 10
    set k "x"
    
    while {$i < 5 && $j > 0} {
        puts "$i\t$j\t$k"
    
        incr i
        incr j -2
        append k x
    }
    

    In fact, you can make liberal use of newlines in a for command too

    for {
        set i 1
        set j 10
        set k "x"
    } {
        $i < 5 && $j > 0 
    } {
        incr i
        incr j -2
        append k x
    } {
        puts "$i\t$j\t$k"
    }