Read config hash-like data into perl hash

前端 未结 1 878
感动是毒
感动是毒 2021-01-24 03:54

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\',         


        
相关标签:
1条回答
  • 2021-01-24 04:37

    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 },
             },
    }
    

    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.

    Better Alternative, use a JSON or 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;
    
    0 讨论(0)
提交回复
热议问题