# In my long running program my $dbname = get_db_name_from_some_config_file(); my $dbh = DBI->connect("dbi:SQLite:dbname=$dbname","",""); my $user_id = 1; my $cfg = get_user_specific_config_values_stored_in_db($user_id); for my $obj_id (0 .. 2 million) { my $obj = new Obj(dbh => $dbh, cfg => $cfg, obj_id => $obj_id); $obj->very_long_complicated_program(); } # In a nearby module Obj.pm sub new { my ($class, %args) = @_; my $dbh = $args{dbh} my $cfg = $args{cfg}; my $obj_id = $args{obj_id}; my $in = { dbh => $dbh, cfg => $cfg, foo => {}, bar => {}, }; my $self = bless $in, $class; # foo is a result of a different query for every obj_id $in->{foo} = $self->foo($obj_id); # The following part is the only part I am still confused about. # Should I use something like Memoize here? # # bar changes only once per, say, every 5000 objects, # and the resulting query from $self->bar is a very # large set (thousands of rows), so it makes sense to # query the db only when bar changes. So, for obj_id # 0 through 4999, bar remains the same, then for obj_id # 5000 through 9999 a new bar is returned, and so on $in->{bar} = $self->bar($obj_id); return $self; } sub dbh { my $class = shift; return $self->{dbh}; } sub cfg { my $class = shift; return $self->{cfg}; } sub foo { my ($class, $obj_id) = shift; my $cfg = $self->cfg; my $dbh = $self->dbh; my $foo = query_dbh_for_foo_execute($obj_id); $foo = change_parts_of_foo_based_on($cfg); return $foo; } sub bar { my ($class, $obj_id) = shift; my $dbh = $self->dbh; my $bar = query_dbh_for_bar_execute($obj_id); $bar = change_parts_of_bar_based_on($cfg); return $bar; }