【问题标题】:Parsing YAML file using Perl使用 Perl 解析 YAML 文件
【发布时间】:2018-10-31 21:29:31
【问题描述】:

我需要一些帮助来解析以下 config.yml 文件:

yamlFile:    
    map:    
        "[abcd.txt]":    
            - name: John    
            - city: Omaha    
        "[efgh.txt]":    
            - name: Sandra    
            - city: Columbus    
        "[ijkl.txt]":    
            - name: Annie   
            - city: Chicago    

我正在使用以下脚本进行解析。

my $config = LoadFile('config.yml');   
use Data::Dumper;    

for my $conf ( keys %$config ) {    
    print "$conf\n";   
    my $map = $config->{$conf};    
    for my $map1 ( keys %$map ) {    
        print "$map1\n";    
    }    
}    

这将打印以下内容:

yamlFile    
map    

由于 $map1 的键不同,如何进一步获取每个元素的名称和城市?

【问题讨论】:

  • 你使用什么库?
  • 我正在使用 Tiny
  • 我无法重现您的输出,我收到了map\n[abcd.txt]\n[efgh.txt]\n[ijkl.txt] 回复。
  • yaml文件的开头如下。看起来 yamlFile: 在顶部被遗漏了
  • 请更新问题,而不是在 cmets 中描述修复。

标签: perl yaml


【解决方案1】:

以下是如何访问 YAML 配置文件中的项目的示例:

use feature qw(say);
use strict;
use warnings;
use YAML qw(LoadFile);

my $config = LoadFile('config.yml');   
my $map_hash = $config->{yamlFile}{map};    
for my $conf ( keys %$map_hash ) {    
    say $conf;   
    my $elems = $map_hash->{$conf};
    for my $map1 ( @$elems ) {    
        for my $data ( keys %$map1 ) {
            say "$data:", $map1->{$data};
        }
    }    
}    

输出

[ijkl.txt]
name:Annie
city:Chicago
[abcd.txt]
name:John
city:Omaha
[efgh.txt]
name:Sandra
city:Columbus

【讨论】:

  • 在使用“strict refs”时不能使用字符串(“ijkl.txt”)作为HASH ref
  • 我的猜测是这个语句:my $elems = $map_hash->{$conf} 给出了错误。你能检查一下是否正确吗?
  • 错误发生在:for my $data ( keys %$map1 )
  • 那么$map1 很可能不是哈希引用。我们必须找出原因。那么接下来我们查看$elems上面两行的内容。它应该是两个元素的数组引用,每个元素都是一个哈希引用。但是根据您所说的,它似乎已经变成了字符串的数组引用。请检查是否是这种情况。
猜你喜欢
  • 1970-01-01
  • 2020-10-14
  • 2020-07-18
  • 1970-01-01
  • 2021-05-17
  • 2017-04-30
  • 2018-10-13
  • 2016-07-31
  • 2014-11-05
相关资源
最近更新 更多