Even better, there's a standard module for this: Memoize.pm, if the function approach is good enough.
Example:
The BEGIN block isn't necessary, but it'll make the prototype work.use Memoize; BEGIN { *dbh = memoize(sub () { DBI::->connect(...) }) } dbh()->foo; # connect and do foo. dbh()->bar; # use cached object and do bar.
I can't test it, but I don't see why it shouldn't work.
Update: If you really want a variable you may want to check out Tie::Memoize which also is a standard module I think. It uses hashes.
ihb
In reply to Tie::Memoize and Memoize.pm (Was "Re: Does there exist a CPAN module for lazily initialized variables?")
by ihb
in thread Does there exist a CPAN module for lazily initialized variables?
by jryan
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |