Start your script as you would any perl script (e.g. #!/usr/bin/perl, #!/usr/local/bin/perl, #!/opt/bin/perl, [built static? then #!/usr/bin/tkperl], whatever, see the perlrun(1) man page for more information). Throwing the -w warning switch is recommended. The use of the statement use strict; is recommended. Use of the statement use Tk; is required.
A simple "Hello World!" widget script could be written as follows: #!/usr/local/bin/perl -w use strict; use Tk; my $main = new MainWindow; $main->Label(-text => 'Hello World!' )->pack; $main->Button(-text => 'Quit', -command => sub{exit} )->pack; MainLoop;
The MainLoop; statement is the main widget event handler loop and is usually found in perl/Tk scripts (usually near the end of the main procedure after the widgets have been declared and packed). MainLoop; is actually a function call and you may see it written as MainLoop();, &Tk::MainLoop;, &Tk::MainLoop();, etc.
Note the use of the -> infix dereference operator. Most things in calls to perl/Tk routines are passed by reference.
Note also the use of the => operator which is simply a synonym for the comma operator (well it is a bit more than that :-). In other words, the arguments that get passed to Label and Button in the above example are good old perl associative arrays (perl 5 people prefer to call them "hashes" however). Indeed, we might have written the above as: #!/usr/local/bin/perl -w use strict; use Tk; my $main = new MainWindow; $main->Label(-text , 'Hello World!' )->pack; $main->Button(-text , 'Quit', -command , sub{exit} )->pack; MainLoop;
Or even as: #!/usr/local/bin/perl -w use strict; use Tk; my $main = new MainWindow; my %hello = ('-text','Hello World!'); my %quit_com = ('-text' => 'Quit', '-command' => sub{exit}); $main->Label(%hello)->pack; $main->Button(%quit_com)->pack; MainLoop;
Note however, that the use of the => in the first method of writing this script makes it look more "Tcl-ish" :-).
Lastly, we note the extensive use of the my function in most perl/Tk programs. my is roughly equivalent to local in Perl 4 - but is purported to be "faster and safer" as well as much more strictly local in scope. See perlfunc(1) manpage for more information on my.
Other examples of code may be found in the perl5/Tk/demos/ directory and in perl5/Tk/demos/widget_lib/.
(A variant on this scipt called hello is available in the file perl5/Tk/demos/hello in your own pTk distribution. Also, Source code for this and other examples from UserGuide.pod may be found at http://www.perltk.org/contrib/pod/. To load code from the web save as a local filename, edit the first line to point to your perl interpreter, then: chmod u x filename, then execute: filename.)
(另外,在你的pTk的安装包中的demos/目录中有一个名为hello的脚本,实际上就和上面的例子很相似。要使用网页上的代码,你首先要把它保存为一个本地的文件如filename,然后修改它的第一行为你的系统中的Perl解释器的位置,最后:chmod u x filename,这样就可以直接运行filename了。——译者注:如果想省事,其实可以存下来以后就直接使用:perl filename来运行!:-P)