Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: RFC: Practical closure example: Spreadsheet writer

by hilitai (Monk)
on Aug 04, 2007 at 20:23 UTC ( [id://630664]=note: print w/replies, xml ) Need Help??


in reply to RFC: Practical closure example: Spreadsheet writer

Thanks for writing this - I found it interesting. I recently needed to write something that ended up including the first practical use of a closure that I've ever done - I needed to be able to look up a value from a hash table many times, in several different subroutines, but I didn't want to either (a) make the hash global, or (b) have the hash reloaded in each sub.

It was the first time I realized that, hey, closures could be quite useful (my example below).

my $monthConverter = monthConverterFactory(); ... my $moNum = &$monthConverter($mo); if ($moNum > $currentDate[1]) { $y = $currentDate[2] - 1; } ... # Use a closure here, so we don't have to load this private # data more than once. sub monthConverterFactory { my %months = ( Jan => 0, Feb => 1, Mar => 2, Apr => 3, May => 4, Jun => 5, Jul => 6, Aug => 7, Sep => 8, Oct => 9, Nov => 10, Dec => 11 ); return sub { my $val = shift; return $months{$val}; } }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://630664]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (7)
As of 2024-04-19 14:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found