in reply to Working with a legable config file
OTOH, hash items are almost as easy to handle than individual variables are. For example, if your hash is %v, then $v{'a'} (or even $v{a}) does the same as your $a would have done.
In that perspective, virtually any Config::* module might do. Or YAML. Even a simple CSV or tab delimited textfile would work.
The next code saves and loads a hash to and from a tab delimited text file — provided the data contains neither a tab or a newline:
Example use:sub save { my($file, $data) = @_; local *FH; open FH, ">$file" or die "Can't open file $file: $!"; local($\, $,) = ("\n", "\t"); foreach my $key (sort keys %$data){ print FH $key, $data->{$key}; } } sub load { my($file) = @_; local *FH; my %hash; open FH, "<$file" or die "Can't open file $file: $!"; local $/ = "\n"; while(<FH>) { chomp; my($key, $value) = split /\t/; $hash{$key} = $value; } return wantarray ? %hash : \%hash; }
Check the contents of the file "data.txt" to see how it's saved.my %one = ( a => 'alpha', z => 'zeta', b => 'beta'); save("data.txt", \%one); my $two = load("data.txt"); # scalar -> hash ref my %three = load("data.txt"); # list -> hash # Dump: shows everything we got: use Data::Dumper; print Dumper \%one, $two, \%three; # Use individual items, as in a normal program: printf "a stands for %s\n", $one{a}; printf "b stands for %s\n", $two->{b}; printf "z stands for %s\n", $three{z};
|
|---|