Flow-control structures: Difference between revisions

no edit summary
No edit summary
No edit summary
Line 128:
 
immediately starts the next iteration of the current innermost loop
 
==[[Tcl]]==
[[Category:Tcl]]
==== exception ====
Tcl's catch command can be used to provide a basic exception-handling mechanism:
if {[catch { ''... code that might give error ...'' } result]} {
puts "Error was $result"
} else {
''... process $result ...''
}
 
==== custom control structures ====
A novel aspect of Tcl is that it's relatively easy to create new control structures (more detail at http://wiki.tcl.tk/685).
Eg. defining a command to perform some operation for each line of an input file:
proc forfilelines {linevar filename code} {
upvar $linevar line ; # connect local variable line to caller's variable
set filechan [open $filename]
while {[gets $filechan line] != -1} {
uplevel 1 $code ; # Run supplied code in caller's scope
}
close $filechan
}
Now use it to print the length of each line of file "mydata.txt":
forfilelines myline mydata.txt {
puts [string length $myline]
}
Anonymous user