ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 输出到终端,尽量使用双引号 ``` puts "hello,world" ``` ## 多行注释 ``` if 0 { 这是第一次使用tcl } puts "上面是多行注释" ``` ## 查看版本号 ``` puts "version:$tcl_version" ``` ## 环境路径 ``` puts "环境路径$env(PATH)" ``` ## tcl启动文件 ``` puts "启动文件:$tcl_rcFileName" ``` ## 数学计算 Tcl默认精度为12位 可以使用tcl_precision特殊变量改变精度 ``` puts [expr 1 + 1 + 5] ``` ## 变量,字符串(list) ``` set var 24 set str {mstring a b c} puts "$var:[lindex $str 1]" ``` ## 关联数组(如同哈希表) ``` set marks(english) 80 puts english:$marks(english) set marks(mathematics) 90 puts mathematics:$marks(mathematics) ``` ## 动态类型,数据类型自动转换 ``` if 0 { TCL是一种动态类型语言。 变量的值可以在需要时被动态地转换为所需的类型。 例如,一个数字5,其被存储为字符串将做的算术运算时被转换为数字。 } set variableA "10" puts $variableA set sum [expr $variableA +20]; puts $sum ``` ## tcl的运算符和c语言基本一样 只有一些细微差别 ``` set a 21 set b 10 set c [expr $a + $b] puts "Line 1 - Value of c is $c\n" set c [expr $a - $b] puts "Line 2 - Value of c is $c\n" set c [expr $a * $b] puts "Line 3 - Value of c is $c\n" set c [expr $a / $b] puts "Line 4 - Value of c is $c\n" set c [expr $a % $b] puts "Line 5 - Value of c is $c\n" ``` ### 注意else的位置和条件是用大括号括起来的 ``` if {10 > 5} { puts "a大于c" } else { puts "a不大于c" } if {!10 || 5} { puts "true" } else { puts "false" } set d [expr 2>3?2 : 3] puts $d set a 100 #check the boolean condition if { $a == 10 } { # if condition is true then print the following puts "Value of a is 10" } elseif { $a == 20 } { # if else if condition is true puts "Value of a is 20" } elseif { $a == 30 } { # if else if condition is true puts "Value of a is 30" } else { # if none of the conditions is true puts "None of the values is matching" } puts "Exact value of a is: $a" ``` ## case语句 注意空格 ``` set grade 2 switch $grade { 1 { puts "grade=1" } 2 { puts "grade=2" } 3 { puts "grade=3" } default { puts "grade=10" } } ``` ## for 循环 ``` for { set a 10} {$a < 20} {incr a} { puts "value of a: $a" } ``` ## 数组 ``` set languages(0) Tcl set languages(1) "C Language" puts $languages(0) puts $languages(1) puts [array size languages] ``` ## 函数 ``` proc helloWorld {} { puts "Hello, World!" } helloWorld proc add {a b} { return [expr $a+$b] } puts [add 10 30] ``` ## 文件操作 ``` set myfile [open "t.txt" w+] puts $myfile "我好细化你" puts $myfile "超级大保健" close $myfile set fp [open "t.txt" r] set file_data [read $fp] puts $file_data close $fp ``` [基础教程](https://www.yiibai.com/tcl/tcl_regular_expressions.html#article-start)