Tcl - Packages

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.

Creating Package

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.

STEP 1 : Creating Code

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

STEP 2 : Creating Package Index

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

STEP 3 : Adding Directory to Autopath

Use the lappend command to add the package to the global list as shown below −

% lappend auto_path "/Users/rajkumar/Desktop/helloworld"

STEP 4 : Adding Package

Next add package to program using package require statement as shown below −

% package require HelloWorld 1.0

STEP 5 : Invoking Procedure

Now, everything being setup, we can invoke our procedure as shown below −

% puts [HelloWorld::MyProcedure]

You will get the following result −


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 −

Kickstart Your Career

Get certified by completing the course

Get Started