PDA

View Full Version : externalize db connection


shyam
07-22-2005, 11:56 AM
hi,
i have a a per/cgi application that interacts with the database using DBI. i don't want to code in the db connection code for all my perl scripts. is there a way in which the db connection is available in a perl file which i can call from any script file when i need it. this also helps when i'm changing my database/dbuser/dbpassword.

thanx
shyam

FishMonger
07-22-2005, 05:24 PM
You could put the connection code a seperate script and call it in with a require statement i.e.,

require dbconnection.pl;

I'd need to test it to be sure but if you're using strict (as you should), you may need to declare the vars with our instead of my.

mlseim
07-22-2005, 08:19 PM
FishMonger ...

What's the difference between "require" and "include"?
I'm never sure which one to use in various situations.
Either one seems to always work OK for me.

FishMonger
07-23-2005, 01:17 AM
FishMonger ...
What's the difference between "require" and "include"?


Since "include" is an SSI command, you probably mean;
What's the difference between "require" and "use"?

The perldoc will give a better explaination than I can.
perldoc -f use
perldoc -f require

edit added:
http://www.unix.org.ua/orelly/perl/advprog/ch06_02.htm
http://www.unix.org.ua/orelly/perl/cookbook/ch12_01.htm
http://www.perl.com/pub/a/2002/05/14/mod_perl.html?page=3

mlseim
07-23-2005, 02:58 AM
Thanks, I see it now.

My problem searching since I didn't use the word "use".

shyam
07-23-2005, 02:36 PM
thanx fishmonger...your solution nearly worked.

the test program i wrote to check it out worked splendidly but, when i ran it from the browser through apache. the page did not display because the dbconnection.pl was not on the %INC anyway. so, i tried giving the absolute path to the dbconnection.pl which worked. and when i tried giving a relative path it failed again.

i do not want to hard-code an absolute path in each of my perl scripts. i'm ok with a relative path though.

shyam

FishMonger
07-23-2005, 04:04 PM
Use the lib pragma; it's used to add directories to Perl's (@INC) search path.
http://www.unix.org.ua/orelly/perl/prog3/ch31_13.htm

Assuming the dbconnection script is in a dir called libperl off of your home dir, you could do this:

use lib "$ENV{HOME}/libperl";
require "dbconnection.pl";

However, since I didn't run a test, I'm not sure if $ENV{HOME} picks up your home dir or the web server account.

Edited:
If $ENV{HOME} doesn't work as expected, you can use

use FindBin qw($Bin);
use lib "$Bin/../lib";

You can read more detailed info on it in the above link.

shyam
07-23-2005, 04:34 PM
hey thanx a lot fishmonger :)

no need to test...it works like a charm for the webserver context just need to replace $ENV{HOME} with $ENV{DOCUMENT_ROOT}

wow...that solved 2 of my problems i can import my templates as well :)