in reply to Re: Cannot read hash variable from file as global...
in thread Cannot read hash variable from file as global...

Hi,

thanks for help. I must be really Perl dumb, it still doesn't work for me. I'd kindly ask for some more help.

If I put your code in Cybro_Items.pm and would like to read %Log_rooms from external file only if it exists and then use Cybro_Items.pm in other main program (for instance test.pl - with "use Cybro_Items;" in it) - what modifications are necessary ?

1. what do I have to change in this case ? In what scope is then %Log_rooms ?

2. can I access content of variable also with $main::Log_rooms{one} ?

Again sorry for dummy questions,

thanks in advance,

Bulek.
  • Comment on Re^2: Cannot read hash variable from file as global...

Replies are listed 'Best First'.
Re^3: Cannot read hash variable from file as global...
by drench (Beadle) on Mar 27, 2009 at 15:47 UTC

    (Just to get this out of the way first: I agree with CountZero and the previous Anonymous answerer that you should consider another way to deal with config files.)

    Back up a bit. Understand that your do(), if successful, puts the last expression in $config_file into the variable $return, but you're throwing that value away in your code!

    This is how I'd go about it:

    First, format your config file as a single hash reference expression like this:

    { default => { 'BM_shutts_south_00' => 1, 'BM_shutt_north_00' => 1, }, };

    I just used your defaults above, so update as necessary.

    To read the config file:

    # define %Log_rooms out here, where it will remain in scope: my %Log_rooms = ( default => { 'BM_shutts_south_00' => 1, 'BM_shutt_north_00' => 1 } ); my $return = do $config_file; if ($return && UNIVERSAL::isa($return, 'HASH')) { # we got a hash reference back, so override the defaults: %Log_rooms = %$return; } else { # do whatever you need to do to recover warn "Using default values.\n"; }