Anda di halaman 1dari 5

proc procedureName {arguments} {

body
}
#!/usr/bin/tclsh
proc helloWorld {} {
puts "Hello, World!"
}
helloWorld
Procedures with multiple arguments
#!/usr/bin/tclsh
proc add {a b} {
return [expr $a+$b]
}
puts [add 10 30]
Procedures with variable arguments

#!/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 }]

Default arguments
#!/usr/bin/tclsh
proc add {a {b 100} } {
return [expr $a+$b]
}
puts [add 10 30]
puts [add 10]

Recursive procedure
#!/usr/bin/tclsh
proc factorial {number} {

if {$number <= 1} {
return 1
}
return [expr $number * [factorial [expr $number 1]]]
}
puts [factorial 3]
puts [factorial 5]

Writing a File

puts command is used to write to an open file.


puts $filename "text to write"

A simple example for writing to a file is shown below.


#!/usr/bin/tclsh
set fp [open "input.txt" w+]
puts $fp "test"
close $fp

Reading a File

set file_data [read $fp]


#!/usr/bin/tclsh
set fp [open "input.txt" w+]
puts $fp "test"
close $fp
set fp [open "input.txt" r]
set file_data [read $fp]
puts $file_data
close $fp

r,w a,r+,w+,a+
The "regexp" command is4 used to match a regular
expression in Tcl. A regular expression is a sequence of
characters that contains a search pattern. It consists of
multiple rules and the following table explains these rules
and corresponding use.

regexp optionalSwitches patterns searchString


fullMatch subMatch1 ... subMatchn

Anda mungkin juga menyukai