Perl/TkFAQ-10.1.如何使用按钮来调用Perl的子程序

王朝perl·作者佚名  2008-05-18
窄屏简体版  字體: |||超大  

原文:

10.1. How do I get a Button to call a Perl subroutine?

You may specify the -command option in the call to create & pack the button as in: $main->Button(-text => 'Print', -command => sub{do_print($filename, $font)} )->pack;

Where sub do_print { } is a subroutine that handles two arguments and is declared elsewhere in the script. A full script example of the use of the above code is presented in the second example(s) in UserGuide.pod

(Full 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 file say ex1.pl, edit the first line to point to your perl interpreter, then change permission: %chmod u+x ex1.pl, then execute the script: %ex1.pl.)

The above method is called the "anonymous subroutine (closure)" method. As discussed in Callback.pod one might have re-written that statement to use the "reference to a sub" method thusly: $main->Button(-text => 'Print', -command => [ \&do_print , $filename, $font ] )->pack;

Note the backslash in front of \&do_print. This causes perl to generate a reference to sub do_print rather than call it. (thanks Jim Stern :-)

译文:

10.1. 如何使用按钮来调用Perl的子程序?

在创建和布置按钮的时候,可以通过设定-command选项来指定某个子程序,例如:

$main->Button(-text => 'Print',

-command => sub{do_print($filename, $font)}

)->pack;

其中,子程序do_print{}是在脚本的其它地方定义的,它可以接受两个参数。UserGuide.pod中的第二个例子就是使用上面的代码的完整的样本。

(译者注:由于原文中提供的链接无法使用,建议大家直接在自己安装的Tk目录中找就可以了。)

在上面的例子中使用了“匿名子程序”(anonymous subroutine)方法。根据Callback.pod中的说明,我们可以用“子程序引用”的方法来改写上面的语句,如下:

$main->Button(-text => 'Print',

-command => [ \&do_print , $filename, $font ]

)->pack;

请注意,在\&do_print之前的反斜杠(\)。这种用法可以使Perl不是调用这个子程序,而是产生出一个指向子程序do_print的引用。(感谢Jim Stem)

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航