English 中文(简体)
Tcl - Packages
  • 时间:2024-11-03

Tcl - Packages


Previous Page Next Page  

Packages are used for creating reusable units of code. A package consists of a collection of files that provide specific functionapty. 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 pbrary, or a combination of both.

Package uses the concept of namespace to avoid colpsion 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 pst 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 pst 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 −

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
Advertisements