There's more than one way to do things | |
PerlMonks |
Re: Help with the concept of closures.by Limbic~Region (Chancellor) |
on Jul 05, 2003 at 23:19 UTC ( [id://271694]=note: print w/replies, xml ) | Need Help?? |
DigitalKitty,
Before explaining the code, let me try and explain what a closure is the way I understand it. A closure is a way to get at data that has gone out of scope. Because the reference count has not reached 0, it persists but is only accessible through the closure.
Ok - lets take the seemingly simple sub shopping list: It creates a lexical variable called $item and then returns a sub. The magic comes in that $item should disapear, but it doesn't since the returned sub keeps the reference count from reaching 0. You still use the lexical $item from elsewhere in the program, but you can still get at it through the closure. Both $ItemInBasket and $newItemInBasket are now code references. They are the referant of the returned anonymous sub, which in turn remembers $item. When they are de-referenced (I prefer the -> notation), they "remember" the $item and shift the argument list to get $otheritem. References and closures are the things Perl OO is made of and that is the next logical step.
If you would like more information - let me know. I am sure there will be far better answers than mine anyway. I should point out that you assume the subs will be called with at least one argument. I know this is only for learning purposes, but coding for unexpected input will save you a great deal of troubleshooting time in the long run.
In Section
Seekers of Perl Wisdom
|
|