Hi Ludwig,
"$total_size" is not out of scope because it is implicitly global
since it was not declared with "my" in the subroutine.
If you remove the initial declaration, the code still works.
If, within the subroutine, you do...
find (sub {my $total_size += -s if -f},'.');
... the code breaks, because "$total_size" would then have a local
scope with each invocation of the subroutine.
Hope that made sense!
Rob
On 12 1, 09, at 10:56 PM, Ludwig Isaac Lim wrote:
> Hi:
>
> I'm having some hard time understand perl closure:
>
> Here's an explanation from Intermediate Perl:
> "The kind of subroutine that can access lexical variables that
> existed at the time we declare it is called a closure .....In Perl
> terms, a closure is just a subroutine that references a lexical
> variable that has gone out of scope".
>
> and here is the sample code:
> use File::Find;
>
> my $total_size = 0;
> find (sub {$total_size += -s if -f},'.');
> print $total_size, "\n";
>
>
> My question is "$total_size" is not out of scope since it is
> declared before "find(sub.." right?
>
> Can we say closures are anonymous coderefs that acesses a pre
> declared variable?
>
> Thanks in advance.
>
> Ludwig
>
>
>
>
>
>
> _________________________________________________
> Philippine Linux Users' Group (PLUG) Mailing List
> http://lists.linux.org.ph/mailman/listinfo/plug
> Searchable Archives: http://archives.free.net.ph
_________________________________________________
Philippine Linux Users' Group (PLUG) Mailing List
http://lists.linux.org.ph/mailman/listinfo/plug
Searchable Archives: http://archives.free.net.ph