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

Help, i will be connecting to many different databases and wanted to soft code the DBH. I have written a package and I pass it database userId and Password, and would want to pass back $dbh_db( the db passed )

my softcode dbh would be ${dbh_."$db"};

my package is:

package tst;

use Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(${dbh_."$db"});

sub connect
{
use DBI;
local ( $db, $i_userid, $i_passwd ) = @_;

${dbh_."$db"} = DBI->connect("DBI:Oracle:$db", $i_userid, $i_passwd);

}

but it does not seem to want to export the ${dbh_."$db"}

"${dbh_."$db"}" is not exported by the tst module at d1.pl line 5

What am I doing wrong? Is this possible?
Any help would be fantastic

Replies are listed 'Best First'.
Re: Exporting sofcoded DBH
by Joost (Canon) on Feb 22, 2008 at 11:28 UTC
    • Exporting happens at "use" time, which is before your connect() method is called, so you won't know which variable to export.
    • instead of referring to a variable by name, it's generally better to use a hash:
      my %handles; $handles{$db} = DBI->connect( ... );
    • Your assumption that a file using your module would want to import a single variable based on some database name that may or may not be created somewhere else is probably in error. How do you know which handle should be exported? And if the calling code must call connect() to specify it, what's the point?
      Many Many Thanks for your replies

      It know works fine
Re: Exporting sofcoded DBH
by moritz (Cardinal) on Feb 22, 2008 at 11:02 UTC
    If you want to use variable variable names, use a hash instead.
      Apologies, but how would I do this?

      Many Thanks

        my %db_handle = ( oracle => DBI->connect("DBI:Oracle:$db", $i_userid, $i_passwd); ); ... my $sth = $db_handle{oracle}->prepare(...);