パッケージ

Tclに標準で付いているパッケージを紹介します。

http

HTTPサーバと通信ができます。
プロキシーサーバを経由してファイルを取得できます。

#!/usr/local/bin/tclsh8.0
package require http 1.0

if {$argc < 2} {
    puts stderr "Usage: $argv0 url file"
    exit 1
}
set url [lindex $argv 0]
set file [lindex $argv 1]
set out [open $file w]

proc progress {token total current} {
    puts -nonewline "."
}

http_config -proxyhost proxy.foo.co.jp -proxyport 8080
set token [http_get $url -progress progress \
	-headers {Pragma no-cache} -channel $out]
close $out

upvar #0 $token state
puts $state(http)
foreach {key value} $state(meta) {
    puts "$key: $value"
}
exit 0

msgcat

メッセージ・カタログを使って英語と日本語の表示を切り替えることができます。

# sample.tcl
package require msgcat
namespace import msgcat::*
msgcat::mcload [file join [file dirname [info script]] msg]
set env(LANG) ja_JP
pack [button .b -text [mc "Push Me"]]
# msg/ja_JP.msg
mcset ja_JP "Push Me" "押してください"

registry

Windowsのレジストリの設定と参照ができます。

package require registry
set key {HKEY_CURRENT_USER\Software\foo}
registry set $key font {MS 明朝}
registry get $key font
=>MS 明朝

dde

Tclのアプリケーション間でメッセージ交換ができます。
Windowsアプリケーション(WorkやExcel等)の操作もできます。

# クライアント
package require dde
button .b -text Send -command {
    dde execute -async TclEval foo {set var Hello!}
}
pack .b
# サーバー
package require dde
dde servername foo
pack [entry .e -textvariable var]

tcltest

テストを行うためのユーティリティ・ツールです。
回帰テストを行うのに便利です。

# alltest.tcl
if {[lsearch [namespace children] ::tcltest] == -1} {
    package require tcltest
    namespace import ::tcltest::*
}

set ::tcltest::testSingleFile false
set ::tcltest::testsDirectory [file dir [info script]]

foreach file [::tcltest::getMatchingFiles] {
    if {[catch {source $file} msg]} {
        puts stderr $msg
    }
}

::tcltest::cleanupTests 1
# sample.test
test Test-1.1 {インデックスのテスト} {
    lindex {test sample1} 1
} sample1

test Test-1.2 {ソートのテスト} {
    lsort {123 abc xyz}
} {123 abc XYZ}
# テスト結果
==== Test-1.2 ソートのテスト FAILED
==== Contents of test case:

    lsort {123 abc xyz}

---- Result was:
123 abc xyz
---- Result should have been:
123 abc XYZ
==== Test-1.2 FAILED

alltest.tcl:	Total	2	Passed	1	Skipped	0	Failed	1
Sourced 0 Test Files.