How to make global vars?

S

Sebastien B.

I'm trying to figure out how to use/make simple global vars.

Since I have multiple scripts that connect to database, I want to use a
seperate file that does the connection and call it in the other scripts; so
something like:

dbiconnect.pl:
use strict;
use DBI;
my $db=dbi_connect.....
1;

and then in the scripts:

use strict;
require 'dbiconnect.pl';
my $somevar=$db->select(...);


problem is that $db isn't global; how do I make it global? Do I need to make
the first script into a pakage? How? (tried it didn't work). None of the
docs are clear on global (cross-file) vars specifically.
 
S

Sam Holden

I'm trying to figure out how to use/make simple global vars.

Since I have multiple scripts that connect to database, I want to use a
seperate file that does the connection and call it in the other scripts; so
something like:

dbiconnect.pl:
use strict;
use DBI;
my $db=dbi_connect.....
1;

and then in the scripts:

use strict;
require 'dbiconnect.pl';
my $somevar=$db->select(...);


problem is that $db isn't global; how do I make it global? Do I need to make
the first script into a pakage? How? (tried it didn't work). None of the
docs are clear on global (cross-file) vars specifically.

perldoc -f my

Notice it specifically says that my declares a local variable, hence
using my to create a global isn't going to work.

perldoc strict

Notice, the "strict vars" section and how to declare or use a non-my
variable when running under it.

perldoc -f our

Notice that while is declares a global variable, it only does so within
a scope, a sort of local global :)


So when under strict you can use "use vars" (which is marked as
obsolete, but the replcement, our, doesn't work for this case). Or you
can use the fully qualified name as in:

---DBIConnect.pm---
package DBIConnect;
use strict;
$DBIConnect::db = ...;
1;
---DBIConnect.pm---

---script---
use strict;
use DBIConnect;
my $sv = $DBIConnect::db->select(...);
---script---


Placing it in a package will make life easier later, trust me.

You could also use the Exporter module to export the db variable so
that you wouldn't have to use the package name in the scripts.

perldoc Exporter
 
S

Sebastien B.

Ok I see; the $DBIConnect::db wasn't part of my earlier attempts; probably
why I couldn't get it to work.

I'll use a package as you've described. Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,143
Messages
2,570,822
Members
47,368
Latest member
michaelsmithh

Latest Threads

Top