Procedures Introduce New Scopes
A procedure introduces a new scope. This normally hides variables unless the global
command (or upvar
or uplevel
) is used. Because Expect depends so much on implicit variables (spawn_id
, timeout
, etc.), Expect commands have a special behavior when it comes to reading variables.
When reading a variable, if a
global
command has declared the variable, the variable is looked up in the global scope. If undeclared, the variable is first looked up in the current scope, and if not found, it is then looked up in the global scope.
The italicized phrase emphasizes how Expect differs from the usual Tcl scoping mechanism. To say this a different way, while reading variables, Expect commands search the global scope for variables if they are not found in the local scope.
In the report
procedure defined above, spawn_id
was defined locally. By the rule just stated, spawn_id
would be found in the local scope. Without the set
command in report
, spawn_id
would be found in the global scope.
This rule can be used to simplify scripts. In the ftp
example on page 237, each time a command was sent to ftp
, it was immediately followed by an expect
to check that the command succeeded.
send "get $file2\r"; expect "220*ftp> "
You can wrap this sequence into a procedure so that each time a command is sent, the response is checked:
proc ftpcmd {cmd} { send "cmd\r" expect "220*ftp> " }
In this procedure, again, spawn_id
is not defined locally, nor is it mentioned in a global
command. Thus, ...
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.