I’ve been having some trouble connecting to my databases using the DBI module. I have a properties file, and in it it specifies whether I want to connect to my oracle or postgres DBs via a simple database=oracle or database=postgres. My property file is set up using the Config::Tiny module, and my variable are set up as so:
my $database = $config->{myDB}->{database};
...
What I don’t understand is even though this works for all my variables, if I try something like this to connect to whichever database is specified in the properties file…
if($database eq "oracle"){
my $dbh = DBI->connect("dbi:Oracle:host=abc123-server;sid=XE;port=1521","User","Pass");
}
elsif($database eq "postgres"){
my $dbh = DBI->connect("dbi:Pg:dbname=pepperoni;host=789xyz-server;port=5444;","Foo","Bar");
}else{
print "Could not connect to a database";
}
…I end up with these errors:
Global symbol "$dbh" requires explicit package name at supportvuloop.pl line 70.
Global symbol "$dbh" requires explicit package name at reportloop.pl line 80.
Global symbol "$dbh" requires explicit package name at reportloop.pl line 81.
Global symbol "$dbh" requires explicit package name at reportloop.pl line 82.
Global symbol "$dbh" requires explicit package name at reportloop.pl line 88.
I can connect to either DB just fine when they are not part of an if condition, any ideas why it would cause errors now?
Your $dbh variable is not declared in correct scope. You should instead declare it before your “if” statement:
They was your code was structured,
$dbhvariable was declared asmyinside the “if” block (and independently, inside “else” block), and therefore the rest of your code did not see those variablesFor further reading:
perldoc my