We can then shorten the subroutines' argument lists considerably:{ my $cgi = CGI->new(); my $session = CGI::Session->new(...); my $dbh = $dbh->connect(...); sub get_cgi { return $cgi; } sub get_session { return $session; } sub get_dbh { return $dbh; } }
The other usual options would be wrapping these subroutines inside a class, so you can store the objects in class or instance variables; or making a package or a (singleton?) class whose only purpose is to initialise, store, and return these objects.MAIN: { my $result = do_something(); print get_cgi()->header().$result; } sub do_something { my $dbh = get_dbh(); my $cgi = get_cgi(); $dbh->foo(...); $cgi->bar(...); my $foo = another_subroutine($somevar, $othervar); return final_result($foo); } sub another_subroutine { my ($somevar, $othervar) = @_; return get_dbh()->baz($somevar, $othervar); } # and so on
In reply to Re: Best practices passing database handles, cgi objects, etc.
by Anonymous Monk
in thread Best practices passing database handles, cgi objects, etc.
by xtpu2
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |