跳转到内容

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://127.0.0.1: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
华夏公益教科书