跳轉到內容

Tcl 程式設計/TCL 和 ADP

來自 Wikibooks,開放世界的開放書籍

Tcl 和 ADP 參考

本參考用於使用 Tcl 與 ADP 頁面,適用於使用 ArsDigita 社群系統(有關詳細資訊,請參閱 OpenACS)設定網站的人員。前半部分只是 Tcl 概述;後半部分涉及 .adp 頁面、自定義標籤以及 AOLServer 資源和引數。

Tcl 概述

[編輯 | 編輯原始碼]

基本 Tcl 語言特性

[編輯 | 編輯原始碼]

; 或換行符 語句分隔符
\ 語句延續(如果為行尾最後一個字元)
# 註釋掉行尾剩餘部分(如果為第一個非空白字元)
var 簡單變數
var(index) 關聯陣列變數
var(i,j) 多維關聯陣列變數
$var 變數替換(還有 ${var}xyz)
[expr 1+2] 命令替換
\char 反斜槓替換
"hello $a" 帶替換的引用
{hello $a} 不帶替換的引用(延遲替換)

Tcl 中唯一的 datatype 是字串。某些命令將引數解釋為數字/布林值;這些格式為:
整數: 12 0xff(十六進位制) 0377(八進位制)
浮點數: 2.1 3. 6e4 7.91e+16
布林值: true false 0 1 yes no

反斜槓替換

[編輯 | 編輯原始碼]

\a 蜂鳴聲 (0x7)
\b 退格 (0x8)
\f 換頁 (0xC)
\n 換行 (0xA)
\r 回車 (0xD)
\t 水平製表符 (0x9)
\v 垂直製表符 (0xB)
\space 空格
\newline 空格
\ddd 八進位制值 (d=0−7)
\xdd 十六進位制值 (d=0−9,a−f)
\c 將 ’\c’ 替換為 ’c’
\\ 反斜槓

運算子和數學函式

[編輯 | 編輯原始碼]

expr 命令按優先順序降序識別這些運算子

− ~ ! unary minus, bitwise NOT, logical NOT
* / % multiply, divide, remainder
+ − add, subtract
<< >> bitwise shift left, bitwise shift right
< > <= >= boolean comparisons
== != boolean equals, not equals
& bitwise AND
^ bitwise exclusive OR
| bitwise inclusive OR
&& logical AND
|| logical OR
x ? y : z if x != 0, then y, else z

所有運算子都支援整數。除了以下運算子外,所有運算子都支援浮點數 ~, %, <<, >>, %, ^, 和 |布林運算子也可以用於字串運算元,在這種情況下,將使用字串比較。如果任何運算元不是有效的數字,則會發生這種情況。以下運算子具有與 C 中相同的“惰性求值”
&&, ||, ?
expr 命令識別以下數學函式
abs hypot int double floor ceil fmod round
cos sin tan acos asin atan atan2 cosh sinh tanh
log log10 exp pow sqrt

正則表示式

[編輯 | 編輯原始碼]
regex | regex match either expression
regex* match zero or more of regex
regex+ match one or more of regex
regex? Match zero or one of regex
. any single character except newline
^ match beginning of string
$ match end of string
\c match character c
c match character c
[abc] match set of characters
[^abc] match characters not in set
[a−z] match range of characters
[^a−z] match characters not in range
( ) group expressions

模式通配

[編輯 | 編輯原始碼]
? match any single character
* match zero or more characters
[abc] match set of characters
[a−z] match range of characters
\c match character c
{a,b,...} match any of string a, b, etc.
~ home directory (for glob command)
~user match user’s home directory (for glob command)
Note: for the glob command, a "." at the beginning of a file’s
name or just after "/" must be matched explicitly and all "/"
characters must be matched explicitly.

控制流

[編輯 | 編輯原始碼]
break
Abort innermost containing loop command
case
Obsolete, see switch
continue
Skip to next iteration of innermost containing loop.
exit[returnCode]
Terminate the process, return returnCode (an integer which
defaults to 0) to the system as the exit status.
for start test next body
Looping command where start, next, and body are Tcl command
strings and test is an expression string to be passed to expr
command.
foreach varname list body
The Tcl command string body is evaluated for each item in the
string list where the variable varname is set to the item’s value.
if expr1 [then] body1 [elseif expr2 [then] body2...] [[else] bodyN]
If expression string expr1 evaluates true, Tcl command string
body1 is evaluated. Otherwise if expr2 is true, body2 is
evaluated, and so on. If none of the expressions evaluate to
true, then bodyN is executed.
return [−code code] [−errorinfo info] [−errorcode code] [string]
Return immediately from current procedure with string as return
value.
switch [options] string pattern1 body1 [ pattern2 body2 ...]
The string argument is matched against each of the pattern
arguments in order. As soon as it finds a pattern that matches
string, it evaluates the corresponding Tcl command string body. If
no match is found and the last pattern is the keyword default, its
command string is evaluated
while test body
Evaluates the Tcl command string body as long as expression string
test evaluates to true.

注意:列表索引從 0 開始,可以使用 end 引用列表中的最後一個元素。

concat [arg arg ...]
Returns concatenation of each string
join list [joinString]
Returns string created by joining all elements of list with
joinString.
lappend varName [value value ...]
Appends each value to the end of the list stored in varName.
lindex list index
Returns value of element at index in list.
linsert list index element [element ...]
Returns new list formed by using each arg as an element.
llength list
Returns number of elements in list.
lrange list first last
Returns new list from slice of list at indices first through last
inclusive.
lsearch [mode] list pattern
Returns index of first element in list that matches pattern (−1
for no match). Mode may be −exact, −glob(default) or −regexp.
lsort [switches] list
Returns new list formed by sorting list according to switches.
These are:
−ascii string comparison (default)
−integer integer comparisons
−real floating−point comparisons
−increasing sort in increasing order (default)
−decreasing sort in decreasing order
−command cmd Use command which takes two arguments and returns
an integer less than, equal to, or greater than zero.
split string [splitChars]
Returns a list formed by splitting string at each character in
splitChars.
append varName [value value ...]
Appends each of the given values to the string stored in varName.

format formatString [arg arg ...]
Returns a formatted string generated in the ANSI C sprintf manner.

regexp [switches] exp string [matchVar] [subMatchVar ...]
Returns 1 if the regular expression exp matches part or all of
string, 0 otherwise. If specified, matchVar will be wet to all
the characters in the match and the following subMatchVar’s will
be set to matched parenthesized subexpressions. The −nocase
switch can be specified to ignore case in matching. The −indices
switch can be specified so that matchVar and subMatchVar will be
set to the start and ending indice3s in string of their
corresponding match.

regsub [switches] exp string subSpec varName
Replaces the first portion of string that matches the regular
expression exp with subSpec and places results in varName. Returns
count of number of replacements made. The −nocase switch can be
specified to ignore case in matching. The −all switch will cause
all matches to be substituted for.

scan string formatString varName [varName ...]
Extracts values into given variables using ANSI C sscanf behavior.
string compare string1 string2
Return −1, 0, or 1, depending on whether string1 is
lexicographically less than, equal to, or greater than string2.
string first string1 string2
Return index in string2 of first occurrence of string1 (−1 if not
found).

string index string charIndex
Returns the charIndex’th character in string.

string last string1 string2
Return index in string2 of last occurrence of string1 (−1 if not
found).

string length string
Returns number of characters in string.

string match pattern string
Returns 1 if glob pattern matches string, 0 otherwise.

string range string first last
Returns characters from string at indices first through last
inclusive.

string tolower string
Returns new string formed by converting all chars in string to
lower case.

string toupper string
Returns new string formed by converting all chars in string to
upper case.

string trim string [chars]
Returns new string formed by removing from string any leading or
trailing characters present in the set chars.

string trimleft string [chars]
Same as string trim for leading characters only.

string trimright string [chars]
Same as string trim for trailing characters only.

string wordend string index
Returns index of character just after last one in word at index in
string.

string wordstart string index
Returns index of first character of word at index in string.

subst [−nobackslashes] [−nocommands] [−novariables] string
Returns result of backslash, command, and variable substitutions
on string. Each may be turned off by switch.

Tcl <--> ADP 介面

[編輯 | 編輯原始碼]

在 ADP 頁面中包含 TCL 程式碼

[編輯 | 編輯原始碼]

內聯替換 <%= 評估為要嵌入的文字的 tcl 程式碼 %>

狀態更改程式碼 <% 更改 tcl 環境的 tcl 命令(設定變數、執行 db 查詢等) %>

示例 二加二等於 <%= [expr 2+2] %>

定義自定義標籤

[編輯 | 編輯原始碼]
ns_register_adptag "codeexample" "/codeexample" tcl_adp_codeexample

proc tcl_adp_codeexample {string tagset} {
return "<blockquote>
<code><pre>${string}</pre></code>
</blockquote>
"
}

使用 AOLServer 引數

[編輯 | 編輯原始碼]
[ad_parameter UsersCanCreateRoomsP chat]

在 AOLserver 中使用 tcl 資源

[編輯 | 編輯原始碼]

source−file.tcl − 用於使用特定檔案。

set_the_usual_form_variables
ns_eval [list source $file]
ns_return 200 text/html ok
wget −O − "https://:8000/source−
file.tcl?file=/web/server1/tcl/myfile.tcl"

注意:這對於註冊的標籤更改不起作用。要重新載入所有內容

<%
set dir [ns_info tcllib]
set list [exec ls $dir]
foreach file $list {
source $dir/$file
ns_puts "sourced: $file
"}%>

使用 ns_set

[編輯 | 編輯原始碼]

當查詢資料庫時,設定的變數是 ns_set

# ask AOLserver to give us a database connection
set db [ns_db gethandle]
set sql_query "select first_names, last_name
from users
where user_id = $user_id"
# actually send the query to the RDBMS; tell AOLserver we
# expect exactly one row back
set selection [ns_db 1row $db $sql_query]
<pre>
''Getting information out of an ns_set:''
<pre>
set first_names [ns_set get $selection "first_names"]
set last_name [ns_set get $selection "last_name"]
ns_return 200 text/plain "User #$user_id is $first_names $last_name"

處理表單變數

[編輯 | 編輯原始碼]

將表單變數匯入 tcl 或 adp 頁面 set_the_usual_form_variables 直接操作表單 ns_getform

在不退出 ns_write 的情況下執行邏輯。就像 SQL 一樣! [util_decode unknown val1 res1 val2 res2 valN resN defaultresult]

處理 .ini 檔案引數

[編輯 | 編輯原始碼]

ad_parameter ad_parameter name { subsection "" } { default "" }

Returns the value of a configuration parameter set in one of the .ini files in
/web/yourdomain/parameters. If the parameter doesn’t exist, returns the
default specified as the third argument (or empty string if not default is
specified). Note that AOLserver reads these files when the server starts up and
stores parameters in an in−memory hash table. The plus side of this is that
there is no hit to the file system and no need to memoize a call to
ad_parameter. The minus side is that you have to restart the server if you
want to test a change made to the .ini file.

ad_parameter_section ad_parameter_section { subsection "" }

Returns all the vars in a parameter section as an ns_set. Relies on
undocumented AOLserver Tcl API call ns_configsection (analogous C API
call is documented). Differs from the API call in that it returns an empty
ns_set if the parameter section does not exist.








將 tcl 轉換為 adp

[編輯 | 編輯原始碼]

包含子檔案

# Source user−new.adp. We would redirect to it, but we don’t want
# the password exposed!
# source "[ns_url2file "/register/user−new.tcl"]"
# return
ns_adp_include user−new.adp
ns_adp_break
華夏公益教科書