Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
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 };


Comment on Re: Getting a hash from a file
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://830519]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (19)
As of 2015-07-07 15:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (91 votes), past polls