Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Getting a hash from a file

by kikuchiyo (Monk)
on Mar 24, 2010 at 10:39 UTC ( #830519=note: print w/replies, xml ) Need Help??


in reply to Getting a hash from a file

An alternative method would be slurping the file into a string and then eval'ing the string. This way you'd have the resulting hash in the same lexical scope as the rest of your variables (or more precisely, the scope of the "imported" variable will be determined by the place of the declaration, see below).

This method also allows you to "import" more than one variable from the file.

Example:
############# # settings.pl %hash1 = ( a => 1, b => 2, ); %hash2 = ( c => 3, d => 4, ); ############# ############# # main.pl #!/usr/bin/perl -w use strict; use Data::Dumper; my %hash1; # declaring them here my %hash2; { local $/; open(my $fh, '<', 'settings.pl') || die "Can't open settings\n"; my $string = <$fh>; eval $string; close $fh; } print Dumper \%hash1; print Dumper \%hash2; ############# shell$ perl main.pl $VAR1 = { 'a' => 1, 'b' => 2 }; $VAR1 = { 'c' => 3, 'd' => 4 };

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://830519]
help
Chatterbox?
and nobody stirs...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (8)
As of 2017-01-23 07:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you watch meteor showers?




    Results (191 votes). Check out past polls.