TCL LEARN NOTE V2
变量
-
变量赋值
set x 10 #设定x的值为10
-
计算后变量赋值
set a 3 set x [expr $a*3] #[]相当于bash中$()或``,作为一个单独的命令运行
-
转义后赋值
set a 3 set b $a #b=$a rather than b=3
-
变量赋值字符串
多个字符需要用双引号包起来
-
变量的引用
变量引用需要dollar符 # $variable
-
替换
- 命令替换[]
- 反斜线替换
打印puts
-
打印单个字符
puts $variable or puts string
-
打印字符串
打印字符串需要用{},将字符串用{}或“”包起来
If the string has more than one word, you must enclose the string in double quotes or braces ({}). A set of words enclosed in quotes or braces is treated as a single unit, while words separated by whitespace are treated as multiple arguments to the command. Quotes and braces can both be used to group several words into a single unit. However, they actually behave differently. In the next lesson you'll start to learn some of the differences between their behaviors. Note that in Tcl, single quotes are not significant, as they are in other programming languages such as C, Perl and Python. https://www.tcl.tk/man/tcl8.5/tutorial/Tcl1.html
-
双引号和大括号的区别
- 双引号允许替换,格式化输出
- 大括号不允许替换
TCL数组
-
基本语法
#数组语法 set arrayname(index) value #连续赋值 array set arrayname[list index1 value1 index2 value2] #数组调用 $arrayname(index)
数组索引中如果有空格,需要特殊处理
-
多维数组
set arrayname(x,y) value
-
关联数组
set arrayname(index_str) value
-
数组大小
array size arrayname
-
数组索引
array names arrayname
-
数组是否存在
array exist arrayname
-
数组索引和值
array get arrayname
-
数组移除
array unset arrayname
-
打印数组parray
parray arrayname
算数运算符
符号 | 描述 |
---|---|
+ | 加法 |
- | 减法 |
* | 乘法 |
/ | 除法 |
% | 模运算 |
** | 幂指数运算 |
关系运算符
关系为真时返回1否则返回0
符号 | 描述 |
---|---|
> | 大于 |
>= | 大于等于 |
< | 小于 |
<= | 小于等于 |
== | 等于 |
!= | 不等于 |
#!/usr/bin/bash
set x 9
set y 21
if {$x == $y} {
puts "x equal to y"
}
if {$x >= $y} {
puts "x large or equal to y"
}
if {$x > $y} {
puts "x large than y"
}
if {$x <= $y} {
puts "x is less or equal to y"
}
if {$x < $y} {
puts "x is less than y"
}
if {$x != $y} {
puts "x is nonequal to y"
}
逻辑运算符
符号 | 描述 |
---|---|
&& | 逻辑与 |
|| | 逻辑或 |
! | 逻辑非 |
位运算符
符号 | 描述 |
---|---|
& | 按位与 |
| | 按位或 |
~ | 按位取反 |
^ | 按位异或 |
<< | 左移 |
>> | 右移 |
三元操作符
?:
y = [expr ($x > 7)? $x:7]
条件判断if
if {condition_is_true} {
code_blocks
}
# =============================================== #
if{condition_one} {
} else {
}
# =============================================== #
if {condition_one} {
} elseif {condition_two} {
} else {
}