chenino
chenino

Reputation: 454

Import Data from Module

I have given a file testconf.pm , with nothing else in it but

my $item = {

'default'   =>     {

    'General'       =>    { 'item1' => 'config1',
                            'item2' => 'config2'
                          }
                   }
           };

In a second file main.pl , i want to load the hash for next processing steps, I tried some stuff like

use testconfig;
use Data::Dumper;
my $config;
$config = testconfig::item;
print Dumper $config;

But i could not get to use the data from testconf. Unfortunately, i am not able to extend testconf.pm with an exporter or a packagedeclaration, using our instea of my and so on, as this file has to stay like this. How could i get the values out of item in main.pl (btw. i Need to Access the data, not only Dumping it )

Upvotes: 1

Views: 71

Answers (2)

Ben Grimm
Ben Grimm

Reputation: 4371

If the file were not structured to allow do to work, you could read the file, make any necessary changes and eval:

open my $fh, '<', 'testconfig.pm';
$/ = undef;
my $testconfig = <$fh>;
# changes to the $testconfig source go here
my $config = eval $testconfig;

Upvotes: 2

ikegami
ikegami

Reputation: 385496

You specifically told Perl to limit the scope of the variable (where it's seen) to the file, so you can't.

If that's the entire file, you could rely on the fact that the assignment to $item is the last statement of the file by changing

do("testconf.pm")
   or die($@ || $!);

to

my $item = do("testconf.pm")
   or die($@ || $!);

Upvotes: 7

Related Questions