0% found this document useful (0 votes)
45 views

Procedures With Variable Arguments

The document discusses Tcl procedures including defining procedures with arguments, variable arguments, default arguments, recursive procedures, writing to files using puts, reading from files using read, and using regular expressions with regexp. Procedures allow defining reusable blocks of code and taking arguments. Puts writes text to an open file and read retrieves the file contents. Regexp matches patterns using regular expression rules.

Uploaded by

Naveen Silveri
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Procedures With Variable Arguments

The document discusses Tcl procedures including defining procedures with arguments, variable arguments, default arguments, recursive procedures, writing to files using puts, reading from files using read, and using regular expressions with regexp. Procedures allow defining reusable blocks of code and taking arguments. Puts writes text to an open file and read retrieves the file contents. Regexp matches patterns using regular expression rules.

Uploaded by

Naveen Silveri
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 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

You might also like