array set a0 $argv foreach opt {-i -o} { puts "$opt -> $a0($opt)" }
运行
$ ex.tcl -i abc -o xyz -i -> abc -o -> xyz
proc display {args} { parse_proc_arguments -args $args my_arg return [expr $my_arg(-a) + $my_arg(-b)] } define_proc_attribute display -info "process two number" -define_args { {-a "the 1st number" a string required} {-b "the 2nd number" b string required} } display -a 5 -b 6
set FH [open ../rpt/$file r] while {[gets $FH line] >= 0} { puts $line } close $FH
if [regexp {^(\w+)} $line all_match match1] { puts $match1 }
当运行的命令出现错误时, catch语句返回1
if [catch {open file.txt r} FH] { puts "Error: file.txt not opened" } else { puts "open file.txt" while {[gets $FH line] >= 0} { puts $line } }
set a [expr 100 * double(1)/3] # 返回33.333333333333336% # 如果不使用double, 则只会返回整数部分 # [expr 100 * 1/3] 返回33 # [expr 1/3 * 100] 返回0 puts "$a%" # 33.333333333333336% set b [format "%.2f" $a] puts "$b%" # 33.33%
# 四舍五入 set a 2.3 set b [expr round($a)] #注意, 要通过expr调用, 调用时后面要加圆括号 puts $b # 2, 四舍五入2.3变为2 # 生成0~1之间的伪随机小数 set c [expr rand()] # 注意, 要通过expr调用. puts $c # 0.45033995969519 # 生成0~9之间的伪随机整数 set d [expr round(9*rand())] puts $d # 5
# eval 动态执行tcl语句 set cmd "puts 123" eval $cmd # 123 # exec 执行unix shell命令(或windows cmd命令) set a [exec find . -name "run*"] puts $a # 打印出find命令的标准输出
binary用于操作二进制字符串.
包含四个子命令:
binary format: 将普通tcl字符串转换为二进制字符串. binary scan : 将二进制字符串转为普通tcl字符串. binary encode: 将二进制字符串进行编码. binary decode: 将编码后的二进制字符串进行解码.
# 普通tcl字符串, 内容是16进制的字符 set hex_str FF00CC # 将普通tcl字符串$hex转为二进制格式, # H : 表示待处理的字符串中是16进制字符 # * : 表示待处理的字符串list长度任意?? set bin_fmt [binary format H* $hex_str] # 将二进制数据($bin_fmt)转为普通tcl字符串, 存储到变量$bits中 binary scan $bin_fmt B* bits # 打印$bits puts $bits ;# 1111111110000000011001100 # 将$bits格式化为特定长度的str, %0*s, 中的*, 表示通过变量指定长度 set width 28 set bits_28 [format "%0*s" $width, $bits] puts $bits_28 ; 00001111111110000000011001100 #遍历$bits_28 set len [string length $bits_28] for {set i 0} {$i<=[expr $len-1]} {incr i} { set i_str [expr $len-1-$i] puts "$i -> [string index $bits_28 $i_str]" } # 0 -> 0 # 1 -> 0 # 2 -> 1 # 3 -> 1 # 4 -> 0 # 5 -> 0 # 6 -> 1 # 7 -> 1 # 8 -> 0 # 9 -> 0 # 10 -> 0 # 11 -> 0 # 12 -> 0 # 13 -> 0 # 14 -> 0 # 15 -> 0 # 16 -> 1 # 17 -> 1 # 18 -> 1 # 19 -> 1 # 20 -> 1 # 21 -> 1 # 22 -> 1 # 23 -> 1 # 24 -> 0 # 25 -> 0 # 26 -> 0 # 27 -> 0