Tcl语言基本语法

0.注释

  • Tcl中的注释需要以#开始,且#应位于命令位置的第一个字符,如果一行命令后接分号说明该行命令结束,再分号后加#也可起到注释作用
  • Tcl中的续行通过反斜杠来实现,但反斜杠后不能跟其他字符

1.设置变量

建立一个名为example.tcl的文件,在文件中输入如下指令:

set name example
#设置变量,该变量名为“name”,值为“example”
echo $name

在shell中使用dcprocheck命令检查语法:

dcprocheck example.tcl

启动dc_shell,运行example.tcl文件查看命令结果:

source example.tcl

得到结果为:

example

2.if else

注意:{}需要用空格间隔

set name example
set num 1
if { $num } {
    echo "num is $num"
} elseif { $name == "example" } {
    echo "name is $name"
} else {
    echo "error"
}

3.switch

set expression 3
switch $expression {
    “nonum” { puts "expression is 0" }
#若变量expression值为字符串“nonum”,则打印引号中的内容
    1 { puts "expression is 1" }
    2 { puts "expression is 2" }
    default { puts "expression is $expression" }
#若变量expression非上述各项,则执行默认情况
}

4.while循环

set i 0
while { $i < 10 } {
    puts " value is $1 "
    incr i 1  ;#这里相当于i = i + 1
}

5.for循环

for { set i 0 } { $i < 10 } { incr i 1 } {
    if { #i == 6 } {
        puts "i is $i "
        continue ;#break
    }
    puts " current i is $i "
}

6.数组/列表的遍历

创建了名为names的数组,内容有3项。foreach是遍历,先把names这个数组的内容依次放进变量num_list,然后依次查看。

set names [ list "ICer" "Coder" 11 ]
foreach num_list $names {
    switch $num_list {
        "ICer" { puts " name 1 is $num_list " }
        "Coder" { puts " name 2 is $num_list " }
        default { puts " $num_list isn't a name "}
    }
}

在dc_shell中执行,结果如下:

name 1 is ICer
name 2 is Coder
11 isn't a name

7.子程序/函数的定义和调用

proc max { a b } { ;#max是函数的名字,a b是参数列表
    if { $a > $b } {
        set y $a ;
    } elseif { $a < $b } {
        set y $b ;
    } else {
        set y "a=b=$a" ;
    }
    return $y ;#返回y的值
}

在dc_shell中调用需要先source example.tcl,然后:

dc_shell> max 2 3
3
dc_shell> max 3 3
a=b=3
dc_shell> max 4 3
4

8.文件的读写

set value2file "hello tcl" ;#定义要写进文件中的变量
set write_file [ open data.txt w+ ] ;#把需要写内容的文件以变量的形式定义
puts $write_file $value2file ;#写的第一步
flush $write_file ;#写的第二步
close $write_file ;#写的最后一步

执行的结果是在当前目录生成文件data.txt,且文件中的内容为“hello tcl”。

set read_value "" ;#设置读变量为空
set read_file [ open data.txt r ]
gets $read_file read_value ;#读取第一步
close $read_file ;#读取第二步
puts $read_value

执行的结果是在dc_sehll中打印出read_value的值,即data.txt中的内容:hello tcl。

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值