Flow-control structures: Difference between revisions

m
m (skipped the extra passage thru old Loop Structures: point directly to Iteration cat)
m (→‎{{header|Tcl}}: formatting)
Line 771:
The <tt>after</tt> facility can be used to execute some code at some future time asynchronously, like this
 
<lang tcl>after 1000 {myroutine x}</lang>
 
which will call "<tt>myroutine</tt>" with parameter "<tt>x</tt>" 1000ms from 'now'; no matter what other code might be running at the time (i.e. "<tt>after</tt>" schedules the execution, then returns and continues program flow with the following code).
Line 777:
The scheduled task can be removed from the scheduler for example with
 
<lang tcl>after cancel myroutine</lang>
 
(other ways are possible).
Line 783:
The correct way to schedule some regularly recurring task in TCL is to incorporate a self-scheduling at the end of the routine. For example the following will produce a clock whose display is updated once a second:
 
<lang tcl>package require Tk
proc update {} {
.clockface configure -text [clock format [clock seconds]]
after 1000 update ; # call yourself in a second
}
# now just create the 'clockface' and call ;update' once:
pack [label .clockface]
update</lang>
 
=== loop control ===
Line 812 ⟶ 813:
close $f
}</lang>
 
=== 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.For definingexample, this example defines a command to perform some operation for each line of an input file:
<lang tcl>proc forfilelines {linevar filename code} {
upvar $linevar line ; # connect local variable line to caller's variable
Line 823 ⟶ 825:
close $filechan
}</lang>
Now we can use it to print the length of each line of file "mydata.txt":
<lang tcl>forfilelines myline mydata.txt {
puts [string length $myline]
Anonymous user