Perl 闭包与 eval 函数的深入解析
闭包的使用方式
闭包在编程中有两种较为独特的使用方式,分别是作为“智能”回调过程和作为迭代器(或流)。
作为“智能”回调
在图形用户界面中,闭包作为回调过程非常方便。例如,使用 Tk 工具包创建按钮时,如果给多个按钮使用同一个普通子程序引用,子程序无法知道是哪个按钮调用了它。而使用闭包作为“智能”回调子程序就能解决这个问题。闭包可以存储特定于按钮的数据(如按钮名称),当子程序被调用时,它可以访问这些数据。
以下是一个示例代码:
use Tk;
# Creates a top level window
$topwindow = MainWindow->new();
# Create two buttons. The buttons print their names when clicked on.
CreateButton($topwindow, "hello");
CreateButton($topwindow, "world");
Tk::MainLoop(); # Dispatch events.
#--------------------------------------------------------------------
sub CreateButton {
my ($parent, $title) = @_;
my($b);
$callback_proc = sub {
print "Button $title press