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

I'm in the process of modularizing a multi-script website. After reading thought some of the tutorials, I thought I understood variable scoping but maybe I'm missing something. In the code snippet below, I want to use global variables, declared in a module, in a second module but found that I needed to include the package name for each global variable.

This seems to work, but am I doing it right way?

## Header.pm package Header; use strict; use DBI; use Exporter; use vars qw(@ISA @EXPORT); @ISA = qw(Exporter); @EXPORT = qw($dbh $userID); our $dbh = DBI->connect('DBI:mysql:database'....); our $userID; 1; ## Some_subs.pm package Some_subs; use strict; use Exporter; use vars qw(@ISA @EXPORT); @ISA = qw(Exporter); @EXPORT = qw(get_data()); sub get_data { my $sql = "select * from table where id=$Header::$userID"; return $Header::dbh->selectrow_array($sql); } 1; ## main ## use strict; use Header; use Some_subs; $userID = 1; my $data = &get_data();
update: Hyphen to underscore. Thanks chromatic
Also corrected the exported variable list

Replies are listed 'Best First'.
Re: Using our $variables across modules
by chromatic (Archbishop) on Feb 13, 2005 at 21:45 UTC

    Add the line use Header; to Some-subs (the hyphen is odd in a package name) to refer to $dbh without the package name.

      the hyphen is odd in a package name

      It also did not work correctly. Changed it to underscore

Re: Using our $variables across modules
by Animator (Hermit) on Feb 13, 2005 at 21:47 UTC
    Well,

    If they are in the same file, then you can leave the package name out, else you have to include it.

    our-variables, are file-scoped, if you use them in another file then they are out of scope, and then you need to refer to the symbol table where they are in (Header:: in your case).

    Also, if you want a global variable which is module-scoped (not file-scoped as our), then you should use: use vars qw/$var1 @array1 %somehash .../;

    Update (after reading the previous post): If the vars are exported then you can use them without the package name. Since export really means that the thingie you export are imported in the currenct namespace.

Re: Using our $variables across modules
by gaal (Parson) on Feb 14, 2005 at 06:02 UTC
    $Header::$userID     # WRONG

    This should be:

    $Header::userID      # only one sigil