tsvik_t has asked for the wisdom of the Perl Monks concerning the following question:

hi there,
I put in the BEGIN function a connection to the database, lets say:
BEGIN { $dbh = DBI->connect($DNS, "login", "password") }
and I use strict, how can I use my connection ($dbh) latter on the program?

Thanks Tsvika

Edit by tye

Replies are listed 'Best First'.
Re: use strict ans begin
by Abigail-II (Bishop) on Jul 17, 2002 at 11:30 UTC
    What exactly is the problem?
    my $dbh; BEGIN {$dbh = DBI -> connect (...)} ... $dbh -> prepare (...);
    will work fine.

    But why are you using a BEGIN block to set up the database connection? Why not just

    my $dbh = DBI -> connect (...);
    And if you really want to place it inside a block, I suggest using an INIT block.

    Abigail

Re: use strict ans begin
by jmcnamara (Monsignor) on Jul 17, 2002 at 11:30 UTC

    You could use the vars pragma to declare a global variable. Or in Perl 5.6.0 or later you can use the our keyword:
    #!/usr/bin/perl -w use strict; use vars '$dbh'; # In Perl >= 5.6.0: # our $dbh; BEGIN { $dbh = DBI->connect($DNS, "login", "password"); }

    --
    John.

      Why would you want to use a package variable and not a lexical one?

      Abigail


        You are right. There isn't any obvious reason here to use a package variable instead of a lexical, except perhaps to demonstrate a hole in your knowledge. :-)

        I didn't know that you could declare a variable with my() before a BEGIN block as in your example.

        --
        John.

Re: use strict ans begin
by Cine (Friar) on Jul 17, 2002 at 12:36 UTC
    If you are using mod_perl I suggest you take a look at Apache::DBI that does this and much more.

    T I M T O W T D I