
Listing 1: The syntax of Tcl commands is quite simple.
A. Command names begin lines, and arguments
possibly grouped by quotes or braces follow:
1 set name {Brent Welch}
2 puts stdout "My name is $name"
B. Command substitution occurs inside
of square brackets:
1 set d [exec date]
2 puts stderr "Error occurred at $d"
Listing 2: Using Tcl/Tk, it is easy to build a graphical user
interface to the ping command.
A. The first version runs ping once
and displays the result:
1 #!/usr/local/bin/wish -f
2 # Ping example #1
3 frame .buttons -borderwidth 10
4 pack .buttons -side top -fill x
5
6 button .buttons.quit -text Quit -command exit
7 button .buttons.ping -text Ping -command Ping
8 pack .buttons.quit .buttons.ping -side right
9
10 frame .f ; pack .f -side top
11 label .f.l -text Host:
12 entry .f.host -width 20 -relief sunken
13 pack .f.l .f.host -side left
14
15 text .log -width 60 -height 10 -bd 2 -relief raised
16 pack .log -side top
17
18 proc Ping {} {
20 set hostname [.f.host get]
21 catch {exec ping $hostname} result
22 .log insert end $result
23 .log insert end \n
24 }
B. The helper script continuously
sends ping's output to the front end
for display:
1 #!/usr/local/bin/wish -f
2 # Install this as "pinghelper"
3 wm withdraw .
4 set hostname [lindex $argv 0]
5 set otherInterp [lindex $argv 1]
6 set in [open "|ping -s $hostname" r]
7 while {[gets $in line] >= 0} {
8 send $otherInterp [list Insert $line]
9 }
10 exit
C. The lines in Listing 2A to change to
integrate the pinghelper:
18 proc Ping {} {
19 global pid
20 set hostname [.f.host get]
21 set pid [exec pinghelper $hostname [winfo name .] &]
22 .buttons.ping configure -text Stop -command Stop
23 }
24 proc Insert { text } {
25 .log insert end $text
26 .log insert end \n
27 .log yview -pickplace end
28 }
29 proc Stop {} {
30 global pid
31 catch {exec kill $pid} result
32 .log insert end $result\n
33 .buttons.ping configure -text Ping -command Ping
34 }
|