Now, somewhere else in the same module, I had an init_connection function, which called the application API to open the connection to the database and to get these identifiers. That init_connection sub called the set_val function, passing it the parameters. Once this is done, the parameters are stored within the two closures. And other subs in my module could call the get_val sub to obtain the stored parameters when needed. This enabled me to make those pieces of data persistent and relatively strongly encapsulated within the module.{ my ($error_buff_p, $connection_id, $transaction_id); my $init_done = 0; sub get_val {return ($error_buff_p, $connection_id, $transaction_id +, $init_done);}; sub set_val { ($error_buff_p, $connection_id, $transaction_id, $ini +t_done) = @_;}; }
It could be made in many other ways (anonymous closures, objects, even lexical variables global to the module, etc.), and I would probably do it differently today (probably with anonymous subs), but I found this to be a quite lightweight solution to my needs at the time.
Having said that, I think that we both agree the anonymous closures are most of the time more useful and more practical. Especially when you want your function to return a code_ref to the caller, as your example shows.
In reply to Re^4: closures: anonymous subs vs function templates?
by Laurent_R
in thread closures: anonymous subs vs function templates?
by 5haun
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |