什么是闭包,“This is a notion out of the Lisp world that says if you define an anonymous function in a particular lexical context, it pretends to run in that context even when it's called outside of the context.”【2】。在面向对象的语言里面,“A closure is a callable object that retains information from the scope in which it was created. From this definition, you can see that an inner class is an object-oriented closure, because it doesn’t just contain each piece of information from the outer-class object ("the scope in which it was created"), but it automatically holds a reference back to the whole outer-class object, where it has permission to manipulate all the members, even private ones.”【3】
先看这个例子:
那么闭包有什么作用呢?以下摘自“Learning Perl Objects, References & Modules”的第6章【1】:
用法一 在subroutine中返回subroutine的引用,通常作为回调函数:
这段代码用于计算某个目录下所包含的所有文件的大小之和.用法二 使用闭环变量作为输入,用作函数生成器,来生成不同的函数指针:
print_bigger_than在这里相当于一个函数生成器,不同的输入变量可以生成不同的函数指针.这里生成了一个可以打印出文件大小大于1024字节文件名的回调函数.用法三 作为静态局部变量使用,提供了c语言静态局部变量的功能:
这里用到了关键字BEGIN. BEGIN的作用就是,当perl编译完这段代码之后,停止当前编译,然后直接进入运行阶段,执行BEGIN块内部的代码.然后再回到编译状态, 继续编译剩余的代码. 这就保证了无论BEGIN块位于程序中的哪个位置,在调用count_down之前,$countdown被确保初始化为10.最后附上一个相当cool的例子,来在“Perl Best Practices”:
参考: