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

I want to access the Values of User_Preferences hash from ::main package.

I need perl monks advice in this

#File name: ConfigFileRead.pm package ConfigFileRead; use strict; use warnings; my %User_Preferences; my $configFile; print("Printing from ConfigFileRead.pm...\n"); print("\nIn namespace: ",__PACKAGE__,"...\n"); sub readConfigFile { print("Printing from readConfigFile()...\n"); my $configFile=shift; open CONFIG,$configFile || die "Missing input file name.\n"; while (<CONFIG>) { chomp; # no newline s/#.*//; # no comments s/^\s+//; # no leading white s/\s+$//; # no trailing white next unless length; # anything left? - skip if the the str +ing is not having any length.. if the length of the default string un +der process is having length greater than 0 then proceed with next st +ep my ($var, $value) = split(/\s*=\s*/, $_, 2); $User_Preferences{$var} = $value; } close(CONFIG); } 1; # don't forget to return a true value from the file

Config.ini file

#Filenname: config.ini # set class C net $NETMASK = '255.255.255.0'; $MTU = 0x128; # Brent, please turn on the modem $DEVICE = 'cua1'; $RATE = 115_200; $MODE = 'adaptive';

Main file : main.pl

use strict; use warnings; require ConfigFileRead; &ConfigFileRead::readConfigFile("config.ini"); print("\nIn namespace: ",__PACKAGE__,"...\n"); # How to access the contents of %User_Preferences ? # Need help

Replies are listed 'Best First'.
Re: How to access the values of variables defined in package from main package
by Corion (Patriarch) on Feb 09, 2010 at 08:05 UTC

    Make your configuration a global variable instead of a lexical variable and you can access it from anywhere:

    package ConfigFileRead; ... use vars qw(%User_Preferences); ...
    # main program ... require ConfigFileRead; use Data::Dumper; print Dumper \%ConfigFileRead::User_Preferences;

    Or, alternatively, make your subroutine readConfigFile return a reference to the configuration:

    # in ConfigRead.pm sub readConfigFile { ... return \%User_Preferences; }; # main program my $config = ConfigFileRead::readConfigFile(); print Dumper $config;
Re: How to access the values of variables defined in package from main package
by Anonymous Monk on Feb 09, 2010 at 06:59 UTC