How Expect Writes Variables In Different Scopes

Although Expect commands look in two scopes when reading variables, only one scope is used when writing variables.

  • When writing a variable, the variable is written in the current scope unless a global command has declared the variable, in which case, the variable is written in the global scope.

This is the usual Tcl behavior, but since it differs from the previous rule, I will describe it in more detail.

In the previous definition of ftpcmd, the expect command looks for ftp to return "220*ftp>“. The expect command, as usual, writes what it finds into expect_out(buffer). However, expect writes the variable into the local scope. That means that the caller does not see the updated expect_out. In the following code, the caller assumes expect_out is not overwritten by ftpcmd.

expect $shellprompt
ftpcmd "get file"
send_user "found shell prompt: $expect_out(buffer)\n"

If you need a procedure to write into the global version of expect_out, then a global command must be used in the procedure. Here is a definition for ftpcmd which does that.

proc ftpcmd {cmd} {
    global expect_out

    send "cmd\r"
    expect "220*ftp> "
}

The rules just described for expect_out hold for spawn_id as well. You need a global command if you want to write the value of spawn_id outside the current procedure. Without a global command, the spawn command writes spawn_id into the local scope. As soon as the procedure returns, spawn_id reverts back to its old definition. In Chapter 4

Get Exploring Expect now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.