in reply to Best practices passing database handles, cgi objects, etc.
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Best practices passing database handles, cgi objects, etc.
by tobyink (Canon) on Feb 18, 2014 at 12:18 UTC | |
by Anonymous Monk on Feb 18, 2014 at 15:23 UTC | |
by tobyink (Canon) on Feb 18, 2014 at 15:46 UTC | |
by Anonymous Monk on Feb 18, 2014 at 13:19 UTC | |
by Anonymous Monk on Feb 18, 2014 at 13:52 UTC | |
by tobyink (Canon) on Feb 18, 2014 at 13:40 UTC |