用户工具

站点工具


语法:tcl语法速查

差别

这里会显示出您选择的修订版和当前版本之间的差别。

到此差别页面的链接

两侧同时换到之前的修订记录前一修订版
后一修订版
前一修订版
语法:tcl语法速查 [2026/01/18 09:40] – [9.1 创建dict] admin语法:tcl语法速查 [2026/11/24 19:14] (当前版本) – [7.12 lrange] user01
行 1: 行 1:
  
-====== tcl语法速查 ======+# tcl语法速查 
 +[tcl_synopsys](语法:tcl_synopsys)
  
-[[语法:tcl_synopsys]] +[tcl_tessent](语法:tcl_tessent)
- +
-[[语法:tcl_tessent]]+
  
  
 参考:  参考: 
-  * [[http://vmcc.vicp.net:9090/tcl86_doc/index.htm|tcl86_doc]]    +  * [tcl86_doc](http://vmcc.vicp.net:9090/tcl86_doc/index.htm)    
  
-  * [[linux:正则表达式]]+  * [正则表达式](linux:正则表达式)
  
-{{ :语法:tcl-tk入门经典_第二版_.pdf |}}+![:语法:tcl-tk入门经典_第二版_.pdf](:语法:tcl-tk入门经典_第二版_.pdf)
  
-{{ :语法:tcl_and_the_tk_toolkit_john_k._ousterhout_.pdf |}}+![:语法:tcl_and_the_tk_toolkit_john_k._ousterhout_.pdf](:语法:tcl_and_the_tk_toolkit_john_k._ousterhout_.pdf)
  
-===== - 查看tcl版本 =====+## - 查看tcl版本
 进入tcl命令tclsh后,输入以下内容: 进入tcl命令tclsh后,输入以下内容:
  
-''info patchlevel''+`info patchlevel`
  
  
 安装tcl: 安装tcl:
  
-<code>yum install -y tcl-devel.x86_64 tcl.x86_64</code> 
  
-===== - regexp正则表达式 =====+``` 
 +yum install -y tcl-devel.x86_64 tcl.x86_64 
 +``` 
  
 +## - regexp正则表达式
 语法: 语法:
  
-''regexp optionalSwitches patterns searchString fullMatch subMatch1 ... subMatchn''+`regexp optionalSwitches patterns searchString fullMatch subMatch1 ... subMatchn`
  
 -nocase : 用于忽略大小写。 -nocase : 用于忽略大小写。
  
  
-==== - 正则表达式规则 ====+### - 正则表达式规则
 更详细的tcl正则表达式规则请查看 http://vmcc.vicp.net:9090/tcl86_doc/re_syntax.htm 更详细的tcl正则表达式规则请查看 http://vmcc.vicp.net:9090/tcl86_doc/re_syntax.htm
  
行 47: 行 49:
  
  
-<code tcl>+ 
 +```tcl
 # [[:<:]]和[[:>:]]与\<和\>和功能一样, 用于匹配word边界 # [[:<:]]和[[:>:]]与\<和\>和功能一样, 用于匹配word边界
 # 三种规则模式都支持[[:<:]] [[:>:]],但仅BRE支持 \< \> # 三种规则模式都支持[[:<:]] [[:>:]],但仅BRE支持 \< \>
行 67: 行 70:
   puts "matched"   puts "matched"
 } }
-</code>+```
  
  
  
-==== - 基本用法 ==== 
  
-<code tcl>+### - 基本用法 
 + 
 +```tcl
  
 set name "day day up" set name "day day up"
行 90: 行 94:
     puts "not matched3"     puts "not matched3"
 } }
 +```
  
-</code> 
  
 运行结果: 运行结果:
-<code>+ 
 +```
 matched matched
 matched2 matched2
 not matched3 not matched3
-</code>+```
  
  
-<code tcl>+ 
 + 
 +```tcl
  
 % set a "cdb" % set a "cdb"
行 111: 行 118:
 haha haha
 % %
 +```
  
-</code> 
  
-==== - {}与""的区别 ====+### - {}与""的区别
   * {}里面不能做变量替换,类似于像\s, [, ]这种功能符不需要在前面加转义   * {}里面不能做变量替换,类似于像\s, [, ]这种功能符不需要在前面加转义
   * ""里面支持变量替换,如果要输入功能符需要在前面加转义,即  \[ 表示为[,  \]表示为], 简单理解该表达式打印出来的值就是我们预期的值,所以在打印的时候要考虑转义。   * ""里面支持变量替换,如果要输入功能符需要在前面加转义,即  \[ 表示为[,  \]表示为], 简单理解该表达式打印出来的值就是我们预期的值,所以在打印的时候要考虑转义。
  
-<code tcl>+ 
 +```tcl
 % set a {\[} % set a {\[}
 \[ \[
行 124: 行 132:
 % set a "\\\[" % set a "\\\["
 \[ \[
 +```
  
-</code> 
  
-<code tcl>+ 
 +```tcl
 % %
 % set a "af" % set a "af"
行 152: 行 161:
 1 1
 % %
 +```
  
-</code> 
  
  
-==== - 匹配多个条件 ==== +### - 匹配多个条件
 匹配多个条件时,直接使用 | 符号 匹配多个条件时,直接使用 | 符号
  
-<code tcl>+ 
 +```tcl
  
 % set a "hello you" % set a "hello you"
行 172: 行 181:
 hit hit
 % %
 +```
  
-</code> 
  
  
  
-==== - submatch, 子匹配 ====+### - submatch, 子匹配
  
-<code tcl>+```tcl
 set name "day day up" set name "day day up"
  
行 190: 行 199:
     puts "m1 = $m1, m2 = $m2, m3 = $m3, m4 = $m4"     puts "m1 = $m1, m2 = $m2, m3 = $m3, m4 = $m4"
 } }
 +```
  
-</code> 
  
 运行结果: 运行结果:
  
-<code>+ 
 +```
 m1 = day day up, m2 = day, m3 = day, m4 = up m1 = day day up, m2 = day, m3 = day, m4 = up
 m1 = day day up, m2 = day, m3 = day, m4 = up m1 = day day up, m2 = day, m3 = day, m4 = up
-</code>+```
  
  
-==== - 非贪婪匹配模式 ==== 
  
 +### - 非贪婪匹配模式
 非贪婪模式,就是在匹配满足的情况下,尽量少的匹配字符。 非贪婪模式,就是在匹配满足的情况下,尽量少的匹配字符。
  
行 208: 行 218:
  
  
-^ 贪婪匹配   ^ 非贪婪匹配   ^ 说明                     ^ 
-| *      | *?      | 非贪婪模式就是在正常匹配模式后面加一个?号  | 
-| +      | +?      |                        | 
-| ?      | ??      |                        | 
-| {m}    | {m}?    |                        | 
-| {m,}   | {m,}?   |                        | 
-| {m,n}  | {m,n}?  |                        | 
  
 +| 贪婪匹配 | 非贪婪匹配 | 说明 |
 +| --- | --- | --- |
 +| * | *? | 非贪婪模式就是在正常匹配模式后面加一个?号 |
 +| + | +? | |
 +| ? | ?? | |
 +| {m} | {m}? | |
 +| {m,} | {m,}? | |
 +| {m,n} | {m,n}? | |
  
  
-==== - regsub正则表达式替换 ====+ 
 +### - regsub正则表达式替换
 语法: 语法:
-''regsub ?switches? exp string subSpec ?varName?''+`regsub ?switches? exp string subSpec ?varName?`
  
-当switches为\\  +当switches为\ 
--all,表示执行多次替换,类似于vim替换的g操作。 \\ +-all,表示执行多次替换,类似于vim替换的g操作。\
 -nocase,表示匹配时忽略大小写。 -nocase,表示匹配时忽略大小写。
  
-<code tcl>+ 
 +```tcl
 # 将abc替换为hello, 并且将替换后的内容保存到变量c # 将abc替换为hello, 并且将替换后的内容保存到变量c
 % regsub  {\w+} "abc def" "hello" c % regsub  {\w+} "abc def" "hello" c
行 242: 行 255:
 "hello def" "hello def"
 % %
-</code>+```
  
  
-==== - 使用变量作为正则表达式 ==== 
  
-<code tcl>+### - 使用变量作为正则表达式 
 + 
 +```tcl
  
 % %
行 263: 行 277:
 1 1
 % %
 +```
  
-</code> 
  
  
-==== - 使用\逃逸 ====+### - 使用\逃逸
  
-<code tcl>+```tcl
 % %
 % set c "da\[0\]\[2\]" % set c "da\[0\]\[2\]"
行 287: 行 301:
 da\a0]\a2] da\a0]\a2]
 % %
-</code>+```
  
  
-==== - 使用\1 \2 ==== 
  
-<code>+### - 使用\1 \2 
 + 
 +```
 % set a "abc.ef" % set a "abc.ef"
 abc.ef abc.ef
行 300: 行 315:
 abc abc
 % %
-</code> +```
-===== - number =====+
  
 +## - number
 integer value: 335 (decimal), 0o517 (octal), 0x14f (hexadecimal), 0b101001111 (binary). integer value: 335 (decimal), 0o517 (octal), 0x14f (hexadecimal), 0b101001111 (binary).
  
-===== - string =====+## - string 
 +### - string length长度
  
-==== - string length长度 ==== +```tcl
- +
- +
-<code tcl>+
 % set len [string length "abc"] % set len [string length "abc"]
 3 3
 % echo $len % echo $len
-</code>+```
  
  
-==== - string compare ====+ 
 +### - string compare
 string compare ?-nocase? ?-length length? string1 string2 string compare ?-nocase? ?-length length? string1 string2
  
 返回结果为0表示相等, 返回-1, 表示string1 < string2,  返回1表示string1 > string2。 返回结果为0表示相等, 返回-1, 表示string1 < string2,  返回1表示string1 > string2。
  
-<code tcl>+ 
 +```tcl
 % string compare "abc" "abc" % string compare "abc" "abc"
 0 0
行 329: 行 344:
 % string compare -nocase "abc" "ABc" % string compare -nocase "abc" "ABc"
 0 0
 +```
  
-</code> 
  
-==== - string cat ====+### - string cat
 Concatenate the given strings just like placing them directly next to each other and return the resulting compound string. If no strings are present, the result is an empty string. Concatenate the given strings just like placing them directly next to each other and return the resulting compound string. If no strings are present, the result is an empty string.
  
-<code tcl>+ 
 +```tcl
 string cat ?string1? ?string2...? string cat ?string1? ?string2...?
  
行 341: 行 357:
 puts $new_str puts $new_str
 #打印hello world #打印hello world
 +```
  
-</code> +### - string replace
-==== - string replace ====+
  
-<code tcl>+```tcl
 string replace string first last ?newstring? string replace string first last ?newstring?
  
行 355: 行 371:
 string replace "0x55,hello" 0 3 "0x33" string replace "0x55,hello" 0 3 "0x33"
 # 将0x55替换为0x33 # 将0x55替换为0x33
 +```
  
-</code> 
 Removes a range of consecutive characters from string, If newstring is specified, then it is placed in the removed character range. Removes a range of consecutive characters from string, If newstring is specified, then it is placed in the removed character range.
-==== - string range ====+### - string range
  
-<code tcl>+```tcl
 string range string first last string range string first last
  
行 366: 行 382:
  
 #返回hell #返回hell
-</code>+``` 
 Returns a range of consecutive characters from string Returns a range of consecutive characters from string
-==== - string repeat ====+### - string repeat
  
-<code tcl>+```tcl
 string repeat string count string repeat string count
  
 string repeat "0" 4 string repeat "0" 4
-</code>+``` 
 Returns string repeated count number of times. Returns string repeated count number of times.
  
-==== - string 大小写转换 ====+### - string 大小写转换
 **转大写** **转大写**
  
-<code>+ 
 +```
 string toupper string ?first? ?last? string toupper string ?first? ?last?
-</code>+``` 
  
 **转小写** **转小写**
-<code>+ 
 +```
 string tolower string ?first? ?last? string tolower string ?first? ?last?
-</code>+```
  
  
-===== - 布尔值 =====+ 
 +## - 布尔值
 https://www.bilibili.com/read/cv16148884/ https://www.bilibili.com/read/cv16148884/
  
-<code>+ 
 +```
 布尔值是编程语言中,普遍存在的一种数据类型。即便没有这种数据类型,也会有这个概念,比如Tcl/Tk。 布尔值是编程语言中,普遍存在的一种数据类型。即便没有这种数据类型,也会有这个概念,比如Tcl/Tk。
  
行 403: 行 426:
 on, off on, off
 数值 1, 0 数值 1, 0
-</code>+``` 
 + 
  
-<code tcl>+```tcl
 % set a "true" % set a "true"
 true true
行 415: 行 440:
 %  if {$a=="true"} {puts haha} %  if {$a=="true"} {puts haha}
 haha haha
-</code>+```
  
-<code>+ 
 + 
 +```
 ## 布尔值单词的一部分,也被认为是布尔值 ## 布尔值单词的一部分,也被认为是布尔值
 # 以下都代表"真" # 以下都代表"真"
行 430: 行 457:
 >> 0 >> 0
 # 但是of可以用来表示"假",因为它是off的一部分 # 但是of可以用来表示"假",因为它是off的一部分
-</code>+```
  
-===== - 进制转换 ===== 
  
-==== - 转为二进制数 ====+## - 进制转换 
 +### - 转为二进制数
  
-<code tcl>+```tcl
 % format "%b" 3 % format "%b" 3
 11 11
行 443: 行 470:
 % format "%b" 0x30 % format "%b" 0x30
 110000 110000
-</code>+```
  
-==== - 转为16进制数 ==== 
  
-<code tcl>+### - 转为16进制数 
 + 
 +```tcl
 % format "%x" 0x30 % format "%x" 0x30
 30 30
行 455: 行 483:
 0x1e 0x1e
 % %
-</code>+``` 
  
  
-==== - 转为10进制数 ====+### - 转为10进制数
  
-<code tcl>+```tcl
 % format "%d" 0x30 % format "%d" 0x30
 48 48
行 466: 行 495:
 30 30
 % %
-</code>+```
  
  
-==== - 产生递进的二进制数 ==== 
  
-<file tcl t3.tcl>+### - 产生递进的二进制数 
 + 
 +~~~tcl t3.tcl
 for {set i 0} {$i <16} {incr i} { for {set i 0} {$i <16} {incr i} {
     set hex_str [format "%04b" $i]     set hex_str [format "%04b" $i]
行 484: 行 514:
     puts ""     puts ""
 } }
-</file>+~~~ 
 运行结果: 运行结果:
  
-<code>+ 
 +```
 hex_str = 0000  bit[3:0] =  0  0  0  0 hex_str = 0000  bit[3:0] =  0  0  0  0
 hex_str = 0001  bit[3:0] =  0  0  0  1 hex_str = 0001  bit[3:0] =  0  0  0  1
行 504: 行 536:
 hex_str = 1110  bit[3:0] =  1  1  1  0 hex_str = 1110  bit[3:0] =  1  1  1  0
 hex_str = 1111  bit[3:0] =  1  1  1  1 hex_str = 1111  bit[3:0] =  1  1  1  1
-</code>+```
  
-==== - com_number set_bits get_bits ==== 
  
-<code tcl>+### - set_bits get_bits 
 + 
 +```tcl
  
 proc h2b {h} { proc h2b {h} {
行 530: 行 563:
         default { set ret 0000 }         default { set ret 0000 }
     }     }
-    # set ret [format "%04b" "0x$h"] 
     return $ret     return $ret
 } }
行 539: 行 571:
     for {set i 0} {$i<$len} {incr i} {     for {set i 0} {$i<$len} {incr i} {
         set tmp [string range $hex_value $i $i]         set tmp [string range $hex_value $i $i]
-        #set bins [string cat $bins [format "%04b" "0x$tmp"]] 
         set tmp [h2b $tmp]         set tmp [h2b $tmp]
         set bins "$bins$tmp"         set bins "$bins$tmp"
行 558: 行 589:
     for {set i 0} {$i<[expr $len/4]} {incr i} {     for {set i 0} {$i<[expr $len/4]} {incr i} {
         set tmp [string range $bins [expr 0+$i*4] [expr 3+$i*4]]         set tmp [string range $bins [expr 0+$i*4] [expr 3+$i*4]]
-        #set hexs [string cat $hexs [format "%0x" "0b$tmp"]] 
         set tmp [format "%0x" "0b$tmp"]         set tmp [format "%0x" "0b$tmp"]
         set hexs "$hexs$tmp"         set hexs "$hexs$tmp"
行 596: 行 626:
     return [bin2hex $replace_bins]     return [bin2hex $replace_bins]
 } }
 +```
 +
  
-</code> 
  
  
-<code tcl>+```tcl
 % %
 % get_bits 32 "0x33" 3 0 % get_bits 32 "0x33" 3 0
行 609: 行 640:
 0x33 0x33
 % %
-</code> +```
-===== - list =====+
  
-==== - 创建list ====+## - list 
 +### - 创建list
  
-<code tcl>+```tcl
 set list_a {1 2 3} set list_a {1 2 3}
 #or #or
 set list_b [list 4 5 6] set list_b [list 4 5 6]
-</code>+```
  
-==== - list 长度 ==== + 
-<code tcl>+### - list 长度 
 + 
 +```tcl
 set len [llength $list_a] set len [llength $list_a]
-</code>+``` 
 + 
 + 
 +### - list index索引
  
-==== - list index索引 ==== +```tcl
-<code tcl>+
 set item0 [lindex $list_a 0] set item0 [lindex $list_a 0]
  
行 641: 行 676:
 % lindex $a end-2 % lindex $a end-2
 3 3
-</code>+```
  
  
-==== - list sort排序 ==== + 
-<code tcl>+### - list sort排序 
 + 
 +```tcl
 set list_a_sorted [lsort $list_a] set list_a_sorted [lsort $list_a]
-</code>+```
  
-<code tcl>+ 
 + 
 +```tcl
 % set a {a0 b0 b2 b3 b10 b20 b22 b30} % set a {a0 b0 b2 b3 b10 b20 b22 b30}
 a0 b0 b2 b3 b10 b20 b22 b30 a0 b0 b2 b3 b10 b20 b22 b30
行 657: 行 696:
 a0 b0 b2 b3 b10 b20 b22 b30 a0 b0 b2 b3 b10 b20 b22 b30
 % %
-</code> +``` 
-==== - list lappend追加 ====+ 
 +### - list lappend追加
 可以用作push功能使用 可以用作push功能使用
  
-<code tcl>+ 
 +```tcl
 lappend listName value lappend listName value
-</code>+``` 
 + 
 + 
 +### - lassign
  
-==== - lassign ==== +```tcl
-<code tcl>+
 % split {a:2} {:} % split {a:2} {:}
 a 2 a 2
行 674: 行 717:
 % puts $m2 % puts $m2
 2 2
-</code> +``` 
-==== - list 嵌套==== + 
-<code tcl>+### - list 嵌套 
 + 
 +```tcl
 % set a {1 2} % set a {1 2}
 1 2 1 2
行 708: 行 753:
 % lindex $a 0; # a只有一个元素,那就是 “1 2”, a已经不是list了。 % lindex $a 0; # a只有一个元素,那就是 “1 2”, a已经不是list了。
 1 2 1 2
-</code>+```
  
-==== - list concat ==== + 
-<code tcl>+### - list concat 
 + 
 +```tcl
 % concat a b {c d e} % concat a b {c d e}
 a b c d e a b c d e
行 723: 行 770:
 % concat a b $b % concat a b $b
 a b u v w a b u v w
-</code> +```
-==== - list 删除第一个元素 ====+
  
 +### - list 删除第一个元素
 可以用作pop功能使用 可以用作pop功能使用
  
-<code tcl>+ 
 +```tcl
 set listName [lrange $listName 1 end] set listName [lrange $listName 1 end]
-</code> +``` 
-==== - linsert 插入 ====+ 
 +### - linsert 插入
 语法: 语法:
-<code tcl>+ 
 +```tcl
 linsert list index ?element element ...? linsert list index ?element element ...?
-</code>+```
  
-This command ''produces a new list'' from list by inserting all of the element arguments just before the index'th element of list. + 
 +This command `produces a new list` from list by inserting all of the element arguments just before the index'th element of list. 
  
  
 举例:  注意,linsert后面需要使用$带变量名。 举例:  注意,linsert后面需要使用$带变量名。
-<code tcl>+ 
 +```tcl
 set oldList {the fox jumps over the dog} set oldList {the fox jumps over the dog}
 set midList [linsert $oldList 1 quick] set midList [linsert $oldList 1 quick]
行 747: 行 799:
 # The old lists still exist though... # The old lists still exist though...
 set newerList [linsert [linsert $oldList end-1 quick] 1 lazy] set newerList [linsert [linsert $oldList end-1 quick] 1 lazy]
-</code>+```
  
  
-==== - lreplace ====+ 
 +### - lreplace
 lreplace — Replace elements in a list with new elements lreplace — Replace elements in a list with new elements
  
行 757: 行 810:
 Replacing an element of a list with another: Replacing an element of a list with another:
  
-<code tcl>+ 
 +```tcl
 % lreplace {a b c d e} 1 1 foo % lreplace {a b c d e} 1 1 foo
 a foo c d e a foo c d e
-</code>+``` 
  
 Replacing two elements of a list with three: Replacing two elements of a list with three:
  
-<code tcl>+ 
 +```tcl
 % lreplace {a b c d e} 1 2 three more elements % lreplace {a b c d e} 1 2 three more elements
 a three more elements d e a three more elements d e
-</code>+``` 
  
  
 Deleting the last element from a list in a variable: Deleting the last element from a list in a variable:
  
-<code tcl>+ 
 +```tcl
 % set var {a b c d e} % set var {a b c d e}
 a b c d e a b c d e
 % set var [lreplace $var end end] % set var [lreplace $var end end]
 a b c d a b c d
-</code>+``` 
  
  
-==== - lrange ====+### - lrange
 lrange — Return one or more adjacent elements from a list lrange — Return one or more adjacent elements from a list
  
行 788: 行 847:
  
 Selecting the first two elements: Selecting the first two elements:
-<code tcl>+ 
 +```tcl
 % lrange {a b c d e} 0 1 % lrange {a b c d e} 0 1
 a b a b
-</code>+``` 
  
 Selecting the last three elements: Selecting the last three elements:
-<code tcl>+ 
 +```tcl
 % lrange {a b c d e} end-2 end % lrange {a b c d e} end-2 end
 c d e c d e
-</code>+``` 
  
 Selecting everything except the first and last element: Selecting everything except the first and last element:
-<code tcl>+ 
 +```tcl
 % lrange {a b c d e} 1 end-1 % lrange {a b c d e} 1 end-1
 b c d b c d
-</code>+```
  
  
-==== - split string to list ====+### - lsearch 
 +lsearch — See if a list contains a particular element
  
 +```tcl
 +-all 返回所有匹配结果
 +-inline 返回搜索到的值,不加返回index, -1表示没匹配到
 +-regexp 用正则匹配
 +
 +% set a [list aa bb cc  bcd]
 +aa bb cc bcd
 +% lsearch -all -regexp $a b
 +1 3
 +% lsearch -all -inline -regexp $a b
 +bb bcd
 +% lsearch  -inline -regexp $a b
 +bb
 +% lsearch -inline -regexp $a {b}
 +bb
 +% lsearch -all -inline -regexp $a {b}
 +bb bcd
 +% lsearch -all -inline -regexp $a {^b$}
 +% lsearch -all -inline -regexp $a {^b}
 +bb bcd
 +
 +```
 +
 +### - split string to list
 split — Split a string into a proper Tcl list split — Split a string into a proper Tcl list
  
-<code tcl>+ 
 +```tcl
 % set a "hello world" % set a "hello world"
 hello world hello world
行 822: 行 912:
 hello hello
 world world
-</code>+```
  
  
-==== - 技巧 ====+ 
 +### - 技巧
 目前还没有找到在递归调用中返回return list的方法, 目前自己使用的是替代方案,采用一个global的list, 然后在递归函数里直接修改该list即可。 目前还没有找到在递归调用中返回return list的方法, 目前自己使用的是替代方案,采用一个global的list, 然后在递归函数里直接修改该list即可。
  
  
-===== - array数组 ===== +## - array数组 
-==== - 创建数组 ==== +### - 创建数组 
-语法: ''set ArrayName(Index) value''+语法: `set ArrayName(Index) value`
  
-<code tcl>+ 
 +```tcl
 set ar(0) 1 set ar(0) 1
 set ar(1) 2 set ar(1) 2
行 841: 行 933:
 puts $ar(1) puts $ar(1)
 puts $ar(2) puts $ar(2)
-</code>+```
  
-==== - array set ====+ 
 +### - array set
 初始化设置array,  参数必须是要偶数个,name-value是成对出现的 初始化设置array,  参数必须是要偶数个,name-value是成对出现的
-<code tcl>+ 
 +```tcl
 % array set c {a 1 b 2 c 3 d 4} % array set c {a 1 b 2 c 3 d 4}
 % echo $c(a) % echo $c(a)
行 855: 行 949:
 % echo $c(d) % echo $c(d)
 4 4
-</code>+```
  
-==== - array size ==== + 
-<code tcl>+### - array size 
 + 
 +```tcl
 % array size c % array size c
 6 6
-</code>+```
  
-==== - array name ====+ 
 +### - array name
 用于搜索array里面是否出现xx name关键字 用于搜索array里面是否出现xx name关键字
  
-<code tcl>+ 
 +```tcl
 array names arrayName ?mode? ?pattern? array names arrayName ?mode? ?pattern?
 Returns a list containing the names of all of the elements in the array that match pattern.  Returns a list containing the names of all of the elements in the array that match pattern. 
 Mode may be one of -exact, -glob, or -regexp.   -glob is default Mode may be one of -exact, -glob, or -regexp.   -glob is default
-</code> +``` 
 +  
  
-<code tcl>+```tcl
 % array set c {a 1 b 2 c 3 d 4} % array set c {a 1 b 2 c 3 d 4}
 % echo $c(a) % echo $c(a)
行 915: 行 1015:
 a a1 a a1
 % %
-</code>+```
  
-==== - array迭代 ==== + 
-<code tcl>+### - array迭代 
 + 
 +```tcl
 for {set i 0} {$i < [array size ar]} {incr i} { for {set i 0} {$i < [array size ar]} {incr i} {
     puts "ar $i : $ar($i)"     puts "ar $i : $ar($i)"
 } }
-</code>+```
  
-==== - array 非数字index ==== + 
-<code tcl>+### - array 非数字index 
 + 
 +```tcl
  
 % set TD(a)   a % set TD(a)   a
行 942: 行 1046:
 % array donesearch TD $id % array donesearch TD $id
 % %
-</code>+``` 
  
  
-==== - 生成连续数字list ====+### - 生成连续数字list
 tcl语言并没有原生类似perl 1..10产生10个连续数字的语法,可以使用类似以下proc的方式产生。 tcl语言并没有原生类似perl 1..10产生10个连续数字的语法,可以使用类似以下proc的方式产生。
  
-<code tcl>+ 
 +```tcl
 proc range {start end} { proc range {start end} {
     set list {}     set list {}
行 957: 行 1063:
 } }
 set numbers [range 1 10]  ;# 生成 1 到 10 的列表 set numbers [range 1 10]  ;# 生成 1 到 10 的列表
-</code>+```
  
  
-===== - dict字典 ===== 
  
 +## - dict字典
 语法 语法
  
-<code tcl>+ 
 +```tcl
 dict set dictname key value dict set dictname key value
 # or  # or 
 dict create key1 value1 key2 value2 .. keyn valuen dict create key1 value1 key2 value2 .. keyn valuen
-</code>+```
  
-==== - 创建dict ==== 
  
-<code tcl>+### - 创建dict 
 + 
 +```tcl
  
 #创建一个空DICT #创建一个空DICT
行 987: 行 1095:
  
 set weigths [dict create "a" 0.2 "b" 0.3 "c" 0.4 "d" 0.66] set weigths [dict create "a" 0.2 "b" 0.3 "c" 0.4 "d" 0.66]
-</code>+``` 
  
 字符串方式直接创建dict 字符串方式直接创建dict
-<code tcl>+ 
 +```tcl
 set mydict { set mydict {
     a {     a {
行 1007: 行 1117:
 set num3 [dict get $b num3] set num3 [dict get $b num3]
 set num4 [dict get $b num4] set num4 [dict get $b num4]
 +```
  
-</code> 
  
-==== - dict unset 删除某个key ==== +### - dict unset 删除某个key 
-<code tcl>+ 
 +```tcl
 dict unset dictionaryVariable key ?key ...? dict unset dictionaryVariable key ?key ...?
  
 dict unset ages lisi;  #删除lisi dict unset ages lisi;  #删除lisi
-</code>+``` 
  
 This operation (the companion to dict set) takes the name of a variable containing a dictionary value and places an updated dictionary value in that variable that does not contain a mapping for the given key. Where multiple keys are present, this describes a path through nested dictionaries to the mapping to remove. At least one key must be specified, but the last key on the key-path need not exist. All other components on the path must exist. The updated dictionary value is returned. This operation (the companion to dict set) takes the name of a variable containing a dictionary value and places an updated dictionary value in that variable that does not contain a mapping for the given key. Where multiple keys are present, this describes a path through nested dictionaries to the mapping to remove. At least one key must be specified, but the last key on the key-path need not exist. All other components on the path must exist. The updated dictionary value is returned.
-==== - dict size大小 ==== +### - dict size大小 
-<code tcl>+ 
 +```tcl
 dict size $weigths dict size $weigths
-</code>+```
  
  
  
-==== - dict for ==== + 
-<code tcl>+### - dict for 
 + 
 +```tcl
 dict for {key value} $dic { dict for {key value} $dic {
     puts "$key--$value"     puts "$key--$value"
 } }
-</code>+``` 
 + 
  
 +### - dict get value
  
-==== - dict get value ==== +```tcl
-<code tcl>+
 dict get $weigths a dict get $weigths a
  
行 1043: 行 1160:
  
 set value [dict get $weigths "aa"] set value [dict get $weigths "aa"]
 +```
  
-</code> 
  
-==== - dict keys ====+### - dict keys
  
-<code tcl>+```tcl
 dict keys $weigths dict keys $weigths
-</code>+```
  
-==== - dict迭代 ==== + 
-<code tcl>+### - dict迭代 
 + 
 +```tcl
 foreach item [dict keys $weigths] { foreach item [dict keys $weigths] {
     set value [dict get $weigths $item]     set value [dict get $weigths $item]
     puts $value     puts $value
 } }
-</code>+```
  
-==== - dict exists ==== + 
-<code tcl>+### - dict exists 
 + 
 +```tcl
 dict exists $weigths a dict exists $weigths a
-</code>+```
  
-==== - dict keys sort排序 ==== + 
-<code tcl>+### - dict keys sort排序 
 + 
 +```tcl
 lsort [dict keys $weigths] lsort [dict keys $weigths]
-</code>+```
  
  
-==== - dict merge, 相当于copy ==== 
  
-<code tcl>+### - dict 按值排序 
 + 
 +```tcl 
 +set d {a 10 b 3 c 25 d 1} 
 + 
 +# 1. 生成嵌套列表 {{a 10} {b 3} {c 25} {d 1}} 
 +set pairs {} 
 +dict for {k v} $d { 
 +    lappend pairs [list $k $v] 
 +} 
 + 
 +# 2. 按第2列(值)数字排序 
 +set sortedPairs [lsort -integer -index 1 $pairs] 
 + 
 +# 3. 展开回扁平字典列表 
 +set flat [concat {*}$sortedPairs] 
 +set newDict [dict create {*}$flat] 
 +puts $newDict 
 +``` 
 + 
 + 
 +封装成proc\ 
 + 
 +```tcl 
 +proc sortDictByVal {dict args} { 
 +    set pairs {} 
 +    dict for {k v} $dict {lappend pairs [list $k $v]} 
 +    return [concat {*}[lsort {*}$args -index 1 $pairs]] 
 +} 
 +# 调用示例 
 +set sortedDict [sortDictByVal $d -integer -decreasing] 
 +``` 
 + 
 +### - dict merge, 相当于copy 
 + 
 +```tcl
 dict merge ?dictionaryValue ...? dict merge ?dictionaryValue ...?
  
 set dict_a [dict merge $dict_b] set dict_a [dict merge $dict_b]
 set dict_a [dict merge $dict_b $dict_c] set dict_a [dict merge $dict_b $dict_c]
-</code>+``` 
  
 Return a dictionary that contains the contents of each of the dictionaryValue arguments. Where two (or more) dictionaries contain a mapping for the same key, the resulting dictionary maps that key to the value according to the last dictionary on the command line containing a mapping for that key. Return a dictionary that contains the contents of each of the dictionaryValue arguments. Where two (or more) dictionaries contain a mapping for the same key, the resulting dictionary maps that key to the value according to the last dictionary on the command line containing a mapping for that key.
行 1084: 行 1242:
  
  
-==== - dict 包 list ==== +### - dict 包 list 
-<code tcl>+ 
 +```tcl
 % set a {1 2} % set a {1 2}
 1 2 1 2
行 1100: 行 1259:
 key_1 . 3 key_1 . 3
 key_1 . 4 key_1 . 4
-</code> +``` 
-===== - 条件判断 & loop循环控制 =====+ 
 +## - 条件判断 & loop循环控制 
 +### - if elseif else
  
-==== - if elseif else ==== +```tcl
-<code tcl>+
 if { $x>0 } { if { $x>0 } {
     puts "x>0"     puts "x>0"
行 1112: 行 1272:
     puts "other"     puts "other"
 } }
-</code>+```
  
-<code tcl>+ 
 + 
 +```tcl
 set isTrue [expr { set isTrue [expr {
     [info exists ::env(SOME_ENV_VAR)] &&     [info exists ::env(SOME_ENV_VAR)] &&
行 1126: 行 1288:
     puts "haha"     puts "haha"
 } }
-</code>+```
  
  
  
-==== - while ==== + 
-<code tcl>+### - while 
 + 
 +```tcl
 set i 8 set i 8
 while { $i>=0 } { while { $i>=0 } {
行 1147: 行 1311:
     }     }
 } }
-</code>+```
  
-==== - for ==== 
  
-<code tcl>+### - for 
 + 
 +```tcl
 set b " " set b " "
 set loop_times 8 set loop_times 8
行 1157: 行 1322:
       lappend b $i       lappend b $i
 } }
-</code>+```
  
  
-==== - foreach ==== + 
-<code tcl>+### - foreach 
 + 
 +```tcl
 set list_b {1 2} set list_b {1 2}
 foreach i $list_b { foreach i $list_b {
     puts "$i"     puts "$i"
 } }
-</code>+``` 
 + 
 + 
 +### - switch
  
-==== - switch ==== +```tcl
-<code tcl>+
 switch $x { switch $x {
     a -     a -
行 1177: 行 1346:
     default {incr t3}     default {incr t3}
 } }
-</code>+``` 
  
 其中 a 的后面跟一个'-'表示使用和下一个模式相同的脚本。 其中 a 的后面跟一个'-'表示使用和下一个模式相同的脚本。
行 1184: 行 1354:
  
  
-===== - proc 过程函数控制 =====+## - proc 过程函数控制 
 +### - 无参数
  
-==== - 无参数 ==== +```tcl
-<code tcl>+
  
 set xxx_var 0x3 set xxx_var 0x3
行 1199: 行 1369:
  
 #  proc中,可以使用global xxx_var来使用proc之外的变量$xxx_var #  proc中,可以使用global xxx_var来使用proc之外的变量$xxx_var
 +```
  
-</code> 
  
-==== - 带参数 ====+### - 带参数
  
-<code tcl>+```tcl
 proc add {a b} { proc add {a b} {
    return [expr $a+$b]    return [expr $a+$b]
 } }
 puts [add 10 30] puts [add 10 30]
-</code>+```
  
-==== - 参数带默认值 ==== + 
-<code tcl>+### - 参数带默认值 
 + 
 +```tcl
 proc add {a {b 100} } { proc add {a {b 100} } {
    return [expr $a+$b]    return [expr $a+$b]
行 1218: 行 1390:
 puts [add 10 30] puts [add 10 30]
 puts [add 10] puts [add 10]
-</code>+``` 
  
  
-==== - 可变个数参数 ====+### - 可变个数参数
  
-<code tcl>+```tcl
 ###########用法1, 传入proc的是一个list变量 ###########用法1, 传入proc的是一个list变量
 % proc calc_sum {numbers} { % proc calc_sum {numbers} {
行 1258: 行 1431:
 missing operator at _@_ missing operator at _@_
 in expression "0 + 70 _@_80" in expression "0 + 70 _@_80"
 +```
  
-</code> 
  
  
-===== - 文件 ===== +## - 文件 
-==== - 文件操作模式 ====+### - 文件操作模式
  
-^ 模式  ^ 说明                             ^ +| 模式 | 说明 | 
-| r   | 只读                             | +| --- | --- | 
-| w   | 只写                             | +| r | 只读 | 
-| a   | 追加写                            | +| w | 只写 | 
-| r+  | 读写,文件必须存在                      | +| a | 追加写 | 
-| w+  | 读写,如果文件存在,就变成0文件。如果文件不存在就创建文件  | +| r+ | 读写,文件必须存在 | 
-| a+  | 读写,如果文件存在,只能追加写。如果文件不存在就创建文件   |+| w+ | 读写,如果文件存在,就变成0文件。如果文件不存在就创建文件 | 
 +| a+ | 读写,如果文件存在,只能追加写。如果文件不存在就创建文件 |
  
-==== - 写文件 ==== +### - 写文件 
-<code tcl>+ 
 +```tcl
 set fp [open "input.txt" w] set fp [open "input.txt" w]
 puts $fp "test0" puts $fp "test0"
 puts $fp "test1" puts $fp "test1"
 close $fp close $fp
-</code>+```
  
-==== - 读文件 ==== 
-=== - 采用read方法 === 
  
 +### - 读文件
 +#### - 采用read方法
 read — Read from a channel, 一下把内容全部读出来 read — Read from a channel, 一下把内容全部读出来
  
-语法:''read channelId numChars''+语法:`read channelId numChars` 
  
-<code tcl>+```tcl
 set fp [open "input.txt" r] set fp [open "input.txt" r]
 set file_data [read $fp] set file_data [read $fp]
 puts "readout: $file_data" puts "readout: $file_data"
 close $fp close $fp
-</code>+```
  
-=== - 采用get一行方法 === 
  
 +#### - 采用get一行方法
 gets — Read a line from a channel, 一行一行地读 gets — Read a line from a channel, 一行一行地读
  
-语法:''gets channelId ?varName?''+语法:`gets channelId ?varName?`
  
-<code tcl>+ 
 +```tcl
 set fp [open "input.txt" r] set fp [open "input.txt" r]
 while { [gets $fp data] >= 0 } { while { [gets $fp data] >= 0 } {
行 1307: 行 1484:
 } }
 close $fp close $fp
-</code>+```
  
  
  
  
-==== - 判断文件 ==== 
-=== - 是否可执行 === 
  
-<code tcl>file executable name</code>+### - 判断文件 
 +#### - 是否可执行 
 + 
 +```tcl 
 +file executable name 
 +``` 
 Returns 1 if file name is executable by the current user, 0 otherwise. On Windows, which does not have an executable attribute, the command treats all directories and any files with extensions exe, com, cmd or bat as executable. Returns 1 if file name is executable by the current user, 0 otherwise. On Windows, which does not have an executable attribute, the command treats all directories and any files with extensions exe, com, cmd or bat as executable.
  
-=== - 是否存在 === +#### - 是否存在 
-<code tcl>file exists name</code>+ 
 +```tcl 
 +file exists name 
 +``` 
 Returns 1 if file name exists and the current user has search privileges for the directories leading to it, 0 otherwise. Returns 1 if file name exists and the current user has search privileges for the directories leading to it, 0 otherwise.
  
-=== - 是否是目录 === +#### - 是否是目录 
-<code tcl>file isdirectory name</code>+ 
 +```tcl 
 +file isdirectory name 
 +``` 
 Returns 1 if file name is a directory, 0 otherwise. Returns 1 if file name is a directory, 0 otherwise.
  
-=== - 是否是普通文件 === +#### - 是否是普通文件
-<code tcl>file isfile name</code> +
-Returns 1 if file name is a regular file, 0 otherwise.+
  
-==== - 文件路径展开 ====+```tcl 
 +file isfile name 
 +```
  
-=== - 带*号匹配展开为绝对路径 ===+Returns 1 if file name is a regular file, 0 otherwise. 
 + 
 +### - 文件路径展开 
 +#### - 带*号匹配展开为绝对路径
  
-<code tcl>+```tcl
 glob — Return names of files that match patterns glob — Return names of files that match patterns
  
 set abs_path [glob ./out/linux_*/*/] set abs_path [glob ./out/linux_*/*/]
-</code>+```
  
-=== - 相对路径替换为绝对路径 ===+ 
 +#### - 相对路径替换为绝对路径
 file normalize name file normalize name
  
 Returns a unique normalized path representation for the file-system object (file, directory, link, etc), whose string value can be used as a unique identifier for it. A normalized path is an absolute path which has all “../” and “./” removed. Also it is one which is in the “standard” format for the native platform. On Unix, this means the segments leading up to the path must be free of symbolic links/aliases (but the very last path component may be a symbolic link), and on Windows it also means we want the long form with that form's case-dependence (which gives us a unique, case-dependent path). The one exception concerning the last link in the path is necessary, because Tcl or the user may wish to operate on the actual symbolic link itself (for example file delete, file rename, file copy are defined to operate on symbolic links, not on the things that they point to). Returns a unique normalized path representation for the file-system object (file, directory, link, etc), whose string value can be used as a unique identifier for it. A normalized path is an absolute path which has all “../” and “./” removed. Also it is one which is in the “standard” format for the native platform. On Unix, this means the segments leading up to the path must be free of symbolic links/aliases (but the very last path component may be a symbolic link), and on Windows it also means we want the long form with that form's case-dependence (which gives us a unique, case-dependent path). The one exception concerning the last link in the path is necessary, because Tcl or the user may wish to operate on the actual symbolic link itself (for example file delete, file rename, file copy are defined to operate on symbolic links, not on the things that they point to).
  
-<code tcl>+ 
 +```tcl
 set abs_path [file normalize ../../] set abs_path [file normalize ../../]
-</code>+```
  
  
  
  
-===== - 随机数 ===== 
  
-<code tcl>+## - 随机数 
 + 
 +```tcl
     set rand_data0 [expr int([expr rand()*10000])]     set rand_data0 [expr int([expr rand()*10000])]
     set rand_data1 [expr int([expr rand()*10000])]     set rand_data1 [expr int([expr rand()*10000])]
行 1360: 行 1555:
     set rand_data3 [expr int([expr rand()*10000])]     set rand_data3 [expr int([expr rand()*10000])]
     set rand_data4 [expr int([expr rand()*10000])]     set rand_data4 [expr int([expr rand()*10000])]
-</code>+``` 
  
  
  
-===== - 调用系统shell命令 =====+## - 调用系统shell命令
  
-<code tcsh>+```tcsh
  
 exec uname -a exec uname -a
 exec mkdir dir_a/subdir_b -p exec mkdir dir_a/subdir_b -p
 +```
  
-</code> 
  
  
  
-===== - info命令 =====+## - info命令
  
-<code tcl>+```tcl
  
 [info script]    #  用于显示当前脚本文件路径。 [info script]    #  用于显示当前脚本文件路径。
行 1385: 行 1581:
 # If pattern is specified, only those procedure names in the current namespace matching pattern are returned. # If pattern is specified, only those procedure names in the current namespace matching pattern are returned.
 # 包括用户自己写的proc函数 # 包括用户自己写的proc函数
 +```
  
-</code> 
  
-==== - 判断变量是否存在 ==== +### - 判断变量是否存在 
-<code tcl>+ 
 +```tcl
 % unset a % unset a
 % if {[info exists a] && $a == 1} { echo "haha" } % if {[info exists a] && $a == 1} { echo "haha" }
行 1400: 行 1597:
 % if {[info exists a] && $a == 1} { echo "haha" } % if {[info exists a] && $a == 1} { echo "haha" }
 % %
-</code>+```
  
-===== - 时间 ===== 
  
-<code tcl>+## - 时间 
 + 
 +```tcl
 clock microseconds     返回毫秒计时 clock microseconds     返回毫秒计时
 clock seconds        返回秒计时 clock seconds        返回秒计时
-</code>+``` 
 + 
  
-<code tcl>+```tcl
 set time1 [clock microseconds] set time1 [clock microseconds]
 puts "time1 = $time1" puts "time1 = $time1"
行 1424: 行 1624:
 20221122-10:28 20221122-10:28
 % %
-</code>+```
  
-===== - tcl command alias别名 ===== 
  
 +## - tcl command alias别名
 tcl支持一个命令有多个alias别名,比如一般来说echo和puts的行为是一样的,但是标准tcl不支持echo命令,可以使用alias来实现这一点。 tcl支持一个命令有多个alias别名,比如一般来说echo和puts的行为是一样的,但是标准tcl不支持echo命令,可以使用alias来实现这一点。
  
-<code tcl>+ 
 +```tcl
 interp alias {} echo {} puts; #为标准tcl puts命令添加一个alias 别名,取名为echo interp alias {} echo {} puts; #为标准tcl puts命令添加一个alias 别名,取名为echo
  
行 1438: 行 1639:
  
 set idx [getIndex delta] set idx [getIndex delta]
-</code>+```
  
  
-===== - json ===== 
  
 +## - json
 参考:  https://core.tcl-lang.org/tcllib/doc/tcllib-1-18/embedded/www/tcllib/files/modules/json/json.html#1 参考:  https://core.tcl-lang.org/tcllib/doc/tcllib-1-18/embedded/www/tcllib/files/modules/json/json.html#1
  
行 1450: 行 1651:
  
  
-==== - json2tcl ==== +### - json2tcl
 json::json2dict工作得还是很好的 json::json2dict工作得还是很好的
  
-<code tcl>+ 
 +```tcl
  
 package require json package require json
行 1491: 行 1692:
     #puts "$key--$value"     #puts "$key--$value"
 } }
 +```
  
  
- +### - tcl2json
-</code> +
- +
-==== - tcl2json ==== +
 以下这段代码是直接可以使用的。来自于 以下这段代码是直接可以使用的。来自于
  
行 1504: 行 1702:
 https://rosettacode.org/wiki/JSON#Tcl https://rosettacode.org/wiki/JSON#Tcl
  
-<code tcl>+ 
 +```tcl
 package require Tcl 8.6 package require Tcl 8.6
 package require json::write package require json::write
行 1566: 行 1765:
 dict set ages misc $addr dict set ages misc $addr
 puts [tcl2json $ages] puts [tcl2json $ages]
 +```
  
-</code> 
  
 输出:输出格式优美,可读性强。 输出:输出格式优美,可读性强。
  
-<code>+ 
 +```
 { {
     "blue"  : ["1","2"],     "blue"  : ["1","2"],
行 1586: 行 1786:
     }     }
 } }
-</code>+```
  
  
-==== - printtcl ====+ 
 +### - printtcl
 此处是为了打印tcl变量的值,支持普通变量的dict & list, 但其实使用json格式来展示打印会更好。 tcl2json 此处是为了打印tcl变量的值,支持普通变量的dict & list, 但其实使用json格式来展示打印会更好。 tcl2json
  
-<code tcl>+ 
 +```tcl
 package require json package require json
    
行 1633: 行 1835:
 } }
 printtcl $d1 printtcl $d1
-  +``` 
-</code>+
  
 输出: 输出:
  
-<code>+ 
 +```
 d1 is : d1 is :
 photos {page 1 pages 726 perpage 3 total 7257 photo {{id 6974156079 owner 74957296 secret 005d743f82 server 7197 farm 8 title Kenya ispublic 1 isfriend 0 isfamily 0} {id 6822988100 owner 52857411 secret 56630c18e8 server 7183 farm 8 title Gedi ispublic 1 isfriend 0 isfamily 0} {id 6822909640 owner 52857411 secret f4e392ea36 server 7063 farm 8 title Local ispublic 1 isfriend 0 isfamily 0}}} stat ok photos {page 1 pages 726 perpage 3 total 7257 photo {{id 6974156079 owner 74957296 secret 005d743f82 server 7197 farm 8 title Kenya ispublic 1 isfriend 0 isfamily 0} {id 6822988100 owner 52857411 secret 56630c18e8 server 7183 farm 8 title Gedi ispublic 1 isfriend 0 isfamily 0} {id 6822909640 owner 52857411 secret f4e392ea36 server 7063 farm 8 title Local ispublic 1 isfriend 0 isfamily 0}}} stat ok
行 1713: 行 1916:
 key:stat key:stat
   ok   ok
-</code>+```
  
-===== - 其它注意 ===== 
  
-  - 标准tcl不支持''echo''命令(打印信息请使用''puts''命令),有些工具支持可能是支持自己作了功能增强。+## - 其它注意 
 +  - 标准tcl不支持`echo`命令(打印信息请使用`puts`命令),有些工具支持可能是支持自己作了功能增强。
  
  
  
语法/tcl语法速查.1768700441.txt.gz · 最后更改: (外部编辑)

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki