Tcl - 函数声明

Tcl - 函数声明 首页 / Tcl/Tk入门教程 / Tcl - 函数声明

创建简单函数的语法如下所示-

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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

玩转Git三剑客 -〔苏玲〕

深度学习推荐系统实战 -〔王喆〕

成为AI产品经理 -〔刘海丰〕

技术面试官识人手册 -〔熊燚(四火)〕

容量保障核心技术与实战 -〔吴骏龙〕

深入剖析Java新特性 -〔范学雷〕

朱涛 · Kotlin编程第一课 -〔朱涛〕

现代React Web开发实战 -〔宋一玮〕

给程序员的写作课 -〔高磊〕

好记忆不如烂笔头。留下您的足迹吧 :)