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

Fellow monks,

I have a set of configuration variables that I run when I first start my application, like this:

my $vars = &load_vars();


The sub loads a text file containing the configuration values (in key/value pairs), and returns a hashref.

What I did this far was to pass this hashref around to just about every sub in my app. So, to create a database connection:

my $dbh = &init_db($vars)


And so on and so forth. Many subs later, I'm thinking that there might be a better way to implement this. I don't want to invoke the &load_vars sub all the time, as it reads from disk, so basically, is there any way to make that hashref persistant across the entire application, without having to pass it around?

Appreciate your input on this...

cheers,
Alex.

Replies are listed 'Best First'.
Re: Persistant variable/data/object?
by antirice (Priest) on Jan 08, 2004 at 19:33 UTC

    Yes. You can do something like:

    package MyConfiguration; our @EXPORT = "get_config"; use base "Exporter"; our $CONFIG = load_vars(); sub get_config() { $CONFIG } sub load_vars { ... } 1;

    Then you just use MyConfiguration; everywhere you need to access the configuration and call get_config whenever you need it.

    Update: liz was kind enough to point out that "use" isn't spelled "base" ;-)

    antirice    
    The first rule of Perl club is - use Perl
    The
    ith rule of Perl club is - follow rule i - 1 for i > 1

      The Object-Oriented gang call this a singleton, but Antirice demonstrates you don't need an object to use the pattern.

      --
      TTTATCGGTCGTTATATAGATGTTTGCA

      Thanks!

      I've done this a zillion times in Java code, but I just couldn't think of a Perl way to do the same thing :) I still need a better grip of the 'use base' thing, as well as the whole @ISA mechanism. Any pointers to good tutorials?

      ++
Re: Persistant variable/data/object?
by freddo411 (Chaplain) on Jan 08, 2004 at 21:31 UTC
    I solve this common problem by directly accessing the hash that is set in an external module (package). Here's the code:

    package G; use strict; use Config::General; use vars qw( %CF ); %G::CF = ParseConfig("./config.dat");

    elsewhere, when I want to make use of the info in the hash

    use strict; my $foo = $G::CF{foo}

    Note the use of Config::General a great config file reader/writer.

    -------------------------------------
    Nothing is too wonderful to be true
    -- Michael Faraday

Re: Persistant variable/data/object?
by NetWallah (Canon) on Jan 08, 2004 at 19:42 UTC
    You could make your has persistant using storable

    "When you are faced with a dilemma, might as well make dilemmanade. "