Updated 2006-11-11 14:29:03

Martin Lemburg:

Stefan Kuhr asked in the comp.lang.tcl newsgroup for a C-like include in tcl [1].

Here one solution:
  # proc to go through the search path of include files
  # to source a given file
  #
  # !! you can use glob pattern in the scriptFileName !!
  #
  proc !include {scriptFileName} {
    global !includePath;

    if {![info exists !includePath]} {
     set !includePath [list [pwd]];
    }

    foreach directory ${!includePath} {
     set filePattern [file join $directory $scriptFileName];
     set fileNames   [glob -nocomplain $filePattern];
     set fileName    [lindex $fileNames 0];

     switch -exact -- [llength $fileNames] {
      0  {}
      1  {
        if {[file readable $fileName]} {
         return [source $fileName];
        }

        error "script file \"$fileName\" not readable";
      }
      default  {
        error "too many files matching \"$scriptFileName\" found";
      }
     }
    }

    error "script file \"$scriptFileName\" not found, check your path";
  }

  # build path from variables or given directories
  # e.g. to be used with variables like auto_path,
  # tcl_library, or if existent tk_library
  #
  # !! you can use glob pattern in directories !!
  #
  proc !includePath {args} {
    global !includePath;

    if {![llength $args]} {
     return ${!includePath};
    }

    foreach arg $args {
     if {[uplevel [list info exists $arg]]} {
      !includePath [uplevel [list set $arg]];
     } elseif {[uplevel #0 [list info exists $arg]]} {
      !includePath [uplevel #0 [list set $arg]];
     } else {
      foreach directory $arg {
        if {[lsearch -exact ${!includePath} $directory] < 0} {
         lappend !includePath $directory;
        }
      }
     }
    }

    return ${!includePath};
  }

  # build search path for include files
  #
  !includePath \
    tcl_library auto_path \
    [pwd] \
    [file join [pwd] lib];

  # source a file inside the search path
  #
  !include dummy.tcl

Category Dev. Tools