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

Hi Monks, I must be missing something but can't see what it is. I'm creating what is essentially a singleton class. These are the two commands I am running on the singleton class.
Encoder::Config::set_config_file($config_file); my $config_obj = Encoder::Config::get_instance;
The code (incomplete) it is calling is below.
package Encoder::Config; my $global_config_file; my $called; my $instance = undef; sub get_instance { my $default_config_file = '../etc/system.ini'; return $instance if defined $instance; $instance = {}; bless $instance; if ($global_config_file) { $instance->load_config($global_config_file); } else { $instance->load_config($default_config_file); } return $instance; } sub set_config_file { $global_config_file = shift; return if $called; $called = 1; }
What's odd is that defined $instance in the get_instance sub always returns true. I went through the debugger, and sure enough, as soon as I enter get_instance my global $instance variable seems to be a hash. Any feedback is greatly appreciated

Replies are listed 'Best First'.
Re: Global and autovivification?
by moritz (Cardinal) on Nov 04, 2008 at 16:05 UTC
    I can't reproduce your problem with the code you gave us. I just added a print statement after the return $instance if defined $instance; line, and a at the end of the program a call to Encoder::Config::get_instance. The print statement is executed (and later it dies because it can't find method load_config, but that's expected).

    So the problem is not in the part of the script that you showed us.

    (In case you haven't already, make sure to use strict; to avoid unintentional magic).

      I think I must've found out at the same time that it does print after the defined test (must've changed something somewhere else to fix that...), but it still does choke if it's put through the debugger. Which is a pain as I'm actually trying to test something else in the sub !
      PROBLEM SOLVED. It turns out that it was a use statement causing me grief