God, I just know I'm doing something stupid.

I'm cleaning up a CGI script which accesses a database. My first version had a database_connect sub which was called by various other subs. The problem, of course, was that sometimes the script needed to access the database more than once (mod_perl isn't an option right now).

So my current plan is to have the script open the database handle once at the beginning and then disconnect at the end, passing the database handle to each sub that needs it. That's exactly what I'm doing with the CGI object, and it works nicely.

It doesn't seem to work with the database handle, however. The error is Can't call method "prepare" on an undefined value, and I understand what it means (I think); I just don't see how my code is generating it. Here's the relevent code:

my $Q = CGI->new(); my $DBH = DBI->connect( <connection string> ) or die 'Error connecting: ' . DBI->errstr; $Q = get_member( $Q, $DBH ); <snip> sub get_member { my $q = shift; my $dbh = shift; my $sth = $dbh->prepare( <query string> ); # here's the error <do stuff> }
The identical code works beautifully if I do either of (while changing $dbh to $DBH, or vice versa ;):
  1. I replace the $dbh = shift; with $dbh = database_connect(); (the database_connect code is identical to the connection code above: copied and pasted).
  2. I take the get_member code out into main
Also, I stole this idea from O'Reilly's CGI Programming with Perl (2nd edition, page 252). I've copied their format exactly, although I haven't tried to run their (pages of) code.

/me braces for clue-sticking. What am I doing wrong?

Thanks muchly
--
man with no legs, inc.


In reply to Passing DBH into sub by legLess

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.