创建简单函数的语法如下所示-
proc procedureName {arguments} { body }
下面是一个简单的函数示例-
#!/usr/bin/tclsh proc helloWorld {} { puts "Hello, World!" } helloWorld
执行以上代码后,将产生以下输出-
链接:https://www.learnfk.comhttps://www.learnfk.com/tcl-tk/tcl-procedures.html
来源:LearnFk无涯教程网
Hello, World!
带参数的函数的示例如下所示-
#!/usr/bin/tclsh proc add {a b} { return [expr $a+$b] } puts [add 10 30]
执行以上代码后,将产生以下输出-
链接:https://www.learnfk.comhttps://www.learnfk.com/tcl-tk/tcl-procedures.html
来源:LearnFk无涯教程网
40
#!/usr/bin/tclsh proc avg {numbers} { set sum 0 foreach number $numbers { set sum [expr $sum + $number] } set average [expr $sum/[llength $numbers]] return $average } puts [avg {70 80 50 60}] puts [avg {70 80 50 }]
执行以上代码后,将产生以下输出-
链接:https://www.learnfk.comhttps://www.learnfk.com/tcl-tk/tcl-procedures.html
来源:LearnFk无涯教程网
65 66
有时将其称为隐式参数-
#!/usr/bin/tclsh proc add {a {b 100} } { return [expr $a+$b] } puts [add 10 30] puts [add 10]
执行以上代码后,将产生以下输出-
链接:https://www.learnfk.comhttps://www.learnfk.com/tcl-tk/tcl-procedures.html
来源:LearnFk无涯教程网
40 110
#!/usr/bin/tclsh proc factorial {number} { if {$number <= 1} { return 1 } return [expr $number * [factorial [expr $number - 1]]] } puts [factorial 3] puts [factorial 5]
执行以上代码后,将产生以下输出-
链接:https://www.learnfk.comhttps://www.learnfk.com/tcl-tk/tcl-procedures.html
来源:LearnFk无涯教程网
6 120
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)