Packages are used for creating reusable units of code. A package consists of a collection of files that provide specific functionality. This collection of files is identified by a package name and can have multiple versions of same files. The package can be a collection of Tcl scripts, binary library, or a combination of both.
Package uses the concept of namespace to avoid collision of variable names and procedure names. Check out more in our next 'namespace' tutorial.
A package can be created with the help of minimum two files. One file contains the package code. Other file contains the index package file for declaring your package.
The list of steps for creating and using package is given below.
Create code for package inside a folder say HelloWorld. Let the file be named HelloWorld.tcl with the code as shown below −
# /Users/rajkumar/Desktop/helloworld/HelloWorld.tcl # Create the namespace namespace eval ::HelloWorld { # Export MyProcedure namespace export MyProcedure # My Variables set version 1.0 set MyDescription "HelloWorld" # Variable for the path of the script variable home [file join [pwd] [file dirname [info script]]] } # Definition of the procedure MyProcedure proc ::HelloWorld::MyProcedure {} { puts $HelloWorld::MyDescription } package provide HelloWorld $HelloWorld::version package require Tcl 8.0
Open tclsh. Switch to HelloWorld directory and use the pkg_mkIndex command to create the index file as shown below −
% cd /Users/rajkumar/Desktop/helloworld % pkg_mkIndex . *.tcl
Use the lappend command to add the package to the global list as shown below −
% lappend auto_path "/Users/rajkumar/Desktop/helloworld"
Next add package to program using package require statement as shown below −
% package require HelloWorld 1.0
Now, everything being setup, we can invoke our procedure as shown below −
% puts [HelloWorld::MyProcedure]
You will get the following result −
HelloWorld
First two steps create the package. Once package is created, you can use it in any Tcl file by adding the last three statements as shown below −
lappend auto_path "/Users/rajkumar/Desktop/helloworld" package require HelloWorld 1.0 puts [HelloWorld::MyProcedure]
You will get the following result −
HelloWorld