Just a small question: does a module to laziliy initialize a tied variable exist on the CPAN? Basically, I have a bunch class variables that are each initialized separately by a relatively expensive operation (database access, reading in an xml file, etc). Since I'm not programming Java, I would feel silly creating a separate Singleton class for each one of these things. All I really want to do is use them like normal variables, and just have them become magically initialized during their first use. As a quick first rev, I hacked this up:
package Tie::LazyInitialized::Hash;
use strict;
require Tie::Hash;
our @ISA = 'Tie::StdHash';
my $sub;
sub TIEHASH {
my ($class, $callback, @args) = @_;
$sub = sub { $callback->(@args) };
bless {}, $class;
}
sub FETCH {
my ($self, $key) = @_;
%$self = %{ $sub->() } unless %$self; # hehe, i wonder if %&$sub w
+ould work?
$self->{$key}
}
1;
But, as soon as I finished typing the last ;, I figured that there *must* be a general CPAN module to do this. However, given that not being able to find things on CPAN is something of a knack of mine, I haven't found anything like what I need. I'd much-much-much rather use a CPAN module than this little hacked up thing. Does anyone know if one exists?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|