深入探索闭包与 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 pressed\n
超级会员免费看
订阅专栏 解锁全文
40

被折叠的 条评论
为什么被折叠?



