in reply to Using "Class Data as Package Variables" to hold a global

Does this eliminate a global?

No, it's just a new hat, but on the other hand, there is nothing wrong on using globals for storing global data and for most apps, configuration data is just global data.

Anyway, I would break the configuration module in two:
a) a generic class abstracting the configuration access logic.
b) a module implementing a singleton to access the global configuration specific to the app.

For example:

class Config::Foo;

package Config::Foo; sub new { my $class = shift; my $fn = shift; ## read the configuration file here ## ... bless $this, $class } sub get { my $this=shift; my $key=shift; my $default=shift; exists $this->{$key} ? $this->{$key} : $default; } sub set { my $this=shift; my $key=shift; my $value=shift; $this->{$key}=$value; } 1; --- package MyApp::Config; use Config::Foo; require Exporter; our @EXPORT=qw(config); our @ISA=qw(Exporter); ## (updated!) my $config; sub config { $config=Config::Foo->new('/etc/myapp.conf') unless defined $config; $config; } 1; --- # and in your app use MyApp::Config; my $foo=config->get(foo); config->set(bar => 'new_bar');

Replies are listed 'Best First'.
Re^2: Using "Class Data as Package Variables" to hold a global
by Forsaken (Friar) on Apr 30, 2005 at 15:14 UTC
    class Config::Foo;

    You had me searching perlfunc there...class? Never seen that before in Perl ;-) I take it you meant package?

    Remember rule one...
      oops, sorry, yes, I meant package!
Re^2: Using "Class Data as Package Variables" to hold a global
by wfsp (Abbot) on Apr 30, 2005 at 17:14 UTC
    salva

    Many thanks. I've had a slight snag with the syntax. If I uncomment the line in the following code I get:

    Can't locate object method "set" via package "config" (perhaps you forgot to load "config"?) at myapp.pl line 9.
    #!/usr/bin/perl use strict; use warnings; use Auto::Config; my $root_local = Auto::Config::config->get(root => 'local'); # This line produces the error message # config->set('root', remote => 'docroot_new'); Auto::Config::config->set('root', remote => 'docroot_new'); print "$root_local\n";

    Do the methods have to be fully qualified like that? Or, more likely, have I goofed?

      I had forgotten to set @ISA, check me original post, I have updated it!
        That fixed it!

        Again, many thanks.