in reply to Help with the concept of closures.
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:#!/usr/bin/perl -w use strict; sub shoppingList { my $item = shift(); return sub { my $otherItem = shift(); print "I need to buy a $item and a $otherItem.\n"; }; } my $itemInBasket = shoppingList( "sweater" ); my $newItemInBasket = shoppingList( "lipstick" ); &$itemInBasket( "pair of shoes" ); &$newItemInBasket( "purse" );
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.
Cheers - L~R
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: Help with the concept of closures.
by aquarium (Curate) on Jul 07, 2003 at 00:35 UTC |