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

Hi, Here is a problem on initialization of globals while embedding Perl inside C.

Consider the following code:

=======================

package Test; require Exporter; @ISA =Exporter; use Config::Inifiles; our $my_config = new Config::Inifiles(-file => "config.ini"); sub my_test { print "[ key = ".$my_config->val("section", "key")."]\n"; }


===============

This piece of code works fine when I invoke my_test function from a Perl file. The correct value for a given key is printed.

But this doesnt work when I invoke my_test through C code.

However, if I move the global initialization code to another Perl module (say globals.pm), and then invoke the function my_test through C, it works.

The new Perl code would be:

====================

Globals.pm

package globals; require Exporter; @ISA = (Exporter); @EXPORT = qw(init, $my_config); use Config::Inifiles; sub init { $my_config = new Config::Inifiles(- file => "config.ini"); } 1;


and Test.pm is as follows:

package Test; require Exporter; @ISA = Exporter; use globals; sub my_test { globals::init(); print "[ key = ".$globals::my_config->val("section", "key")."]\n"; }


Can someone explain this behavior? Why does globals initialization not take place when Perl function is invoked through C code?

Replies are listed 'Best First'.
Re: Global Initialization while embedding Perl
by esskar (Deacon) on Mar 04, 2004 at 05:27 UTC
    well, "our" could be the problem. try my $my_config or use vars qw/$my_config/; and then exporting it if/as needed.
use strict, warnings, and check for failure
by Anonymous Monk on Mar 04, 2004 at 08:00 UTC
    use strict, warnings, and check for failure