Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
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 taking refuge in the Monastery: (11)
As of 2014-09-19 06:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (132 votes), past polls