将类似配置哈希的数据读入perl哈希 [英] Read config hash-like data into perl hash
问题描述
我有一个配置文件 config.txt
like
I have a config file config.txt
like
{sim}{time}{end}=63.1152e6;
{sim}{output}{times}=[2.592e6,31.5576e6,63.1152e6];
{sim}{fluid}{comps}=[ ['H2O','H_2O'], ['CO2','CO_2'],['NACL','NaCl'] ];
我想将它读入perl哈希,
I would like to read this into a perl hash,
my %h=read_config('config.txt');
我已经检出模块 Config :: Hash ,但它不提供相同的输入文件格式。
I have checked out module Config::Hash , but it does not offer the same input file format.
推荐答案
可以自己滚动。使用 Data :: Diver
遍历散列,但也可以手动完成。
Can roll your own. Uses Data::Diver
for traversing the hash, but could do that manually as well.
use strict;
use warnings;
use Data::Diver qw(DiveVal);
my %hash;
while (<DATA>) {
chomp;
my ($key, $val) = split /\s*=\s*/, $_, 2;
my @keys = $key =~ m/[^{}]+/g;
my $value = eval $val;
die "Error in line $., '$val': $@" if $@;
DiveVal(\%hash, @keys) = $value;
}
use Data::Dump;
dd \%hash;
__DATA__
{sim}{time}{end}=63.1152e6;
{sim}{output}{times}=[2.592e6,31.5576e6,63.1152e6];
{sim}{fluid}{comps}=[ ['H2O','H_2O'], ['CO2','CO_2'],['NACL','NaCl'] ];
输出:
Outputs:
{
sim => {
fluid => { comps => [["H2O", "H_2O"], ["CO2", "CO_2"], ["NACL", "NaCl"]] },
output => { times => [2592000, 31557600, 63115200] },
time => { end => 63115200 },
},
}
如果您可以来以一种不使用 eval
一个>,但不知道你的数据,我不能准确地提出一个替代。
Would be better if you could come up with a way to not utilize eval
, but not knowing your data, I can't accurately suggest an alternative.
如果你自己选择数据格式,我建议使用 JSON
或 YAML
用于保存和加载配置数据。
If you're picking the data format yourself, I'd advise using JSON
or YAML
for saving and loading your config data.
use strict;
use warnings;
use JSON;
my %config = (
sim => {
fluid => { comps => [["H2O", "H_2O"], ["CO2", "CO_2"], ["NACL", "NaCl"]] },
output => { times => [2592000, 31557600, 63115200] },
time => { end => 63115200 },
},
);
my $string = encode_json \%config;
## Save the string to a file, and then load below:
my $loaded_config = decode_json $string;
use Data::Dump;
dd $loaded_config;
这篇关于将类似配置哈希的数据读入perl哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!