The
source command will load a file and execute it. This allows a program to be broken up into multiple files, with each file defining procedures and variables for a particular area of functionality. For instance, you might have a file called database.tcl that contains all the procedures for dealing with a database, or a file called gui.tcl that handles creating a graphical user interface with Tk. The main script can then simply include each file using the sourcecommand. More powerful techniques for program modularization are discussed in the next lesson on packages.
This command can be used to:
- separate a program into multiple files.
- make a library file that contains all the procs for a particular set of functions.
- configure programs.
- load data files.
sourcefileName- Reads the script in
fileNameand executes it. If the script executes successfully,sourcereturns the value of the last statement in the script. - If there is an error in the script,
sourcewill return that error. - If there is a return (other than within a
procdefinition) thensourcewill return immediately, without executing the remainder of the script. - If
fileNamestarts with a tilde (~) then$env(HOME)will substituted for the tilde, as is done in thefilecommand.
Example
sourcedata.tcl:
# Example data file to be sourcedset scr [info script]global scr puproc testproc {} { ts "testproc source file: $scr" }set abc 1 returnset aaaa 1
sourcemain.tcl:
set filename "sourcedata.tcl"puts "Global variables visible before sourcing $filename:"puts "[lsort [info globals]]\n"{ puts "testproc does not exisif {[info procs testproc] eq ""} t. sourcing $filename" source $filename }lobal variables visible after sputs "\nNow executing testproc" testproc puts " Gourcing $filename:"obals]]\n"puts "[lsort [info g l
No comments:
Post a Comment