First of all, may I apologize for my lack of perl-fu so I may be doing this wrong.
On Tue, Dec 1, 2009 at 10:56 PM, Ludwig Isaac Lim <[email protected]> wrote: > My question is "$total_size" is not out of scope since it is declared > before "find(sub.." right? Yes and no. Without strict, $total_size would still be in scope because it would be initialized to the first value of +=. Declaring it beforehand demonstrates the dynamic, not necessarily lexical scoping, of Perl in that Perl subs can access variables outside of it. A more useful example of lexical scoping makes a function that generates other functions based on how you initialize it: ---- use strict; sub hellofn { my $subject = @_[0]; return sub { print "Hello $subject!\n" }; } my $helloworld = hellofn ("World"); my $helloburrito = hellofn ("Burrito"); ... some magic... &$helloworld(); #says "Hello World!\n" &$helloburrito(); #says "Hello Burrito!\n" ---- In the above, hellofn is a "closure" - we define it so that we can generate other functions that work similarly. Think of it like a class that, when instantiated, returns an object with a single public method. Each "instantiation" of your closure has its own persistent storage. Paticularly, the "subject" of the first hellofn is stored separately from the subject of the next hellofn generated. You can use closures to make counters, something like: sub gcounter { my $count=0; return sub { print $count+=1, "\n" }} $c1 = gcounter(); $c2 = gcounter(); &$c1(); &$c2(); &$c1(); &$c2(); &$c1(); &$c2(); gcounter is a closure that generates counters which increment a $count variable. But the $count variables in the generated counters will increment independently of each other. This largely depends on the "my" making the $count variable private to gcounter and its subs. > Can we say closures are anonymous coderefs that acesses a pre declared > variable? Something like that. I guess you could think of it as a kind of function template which gives persistent storage. Closure'd variables are private to the functions generated. > > 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 > -- This email is: [ ] actionable [ ] fyi [ ] social Response needed: [ ] yes [ ] up to you [ ] no Time-sensitive: [ ] immediate [ ] soon [ ] none _________________________________________________ Philippine Linux Users' Group (PLUG) Mailing List http://lists.linux.org.ph/mailman/listinfo/plug Searchable Archives: http://archives.free.net.ph

