问题描述
我正在尝试从 YAML 文件中为我的 Perl 脚本获取数据.
以下是类似的示例场景:
让我们考虑一个用于存储员工数据的 YAML 文件.
---emp_name:约翰雇员年龄:27出生日期:1990 年 1 月 1 日其他:- 键1:值1- 键2:值2---emp_name:母鹿雇员年龄:25出生日期:1992 年 1 月 1 日其他:- 键1:值1- 键2:值2---emp_name: foo雇员年龄:22出生日期:1995 年 1 月 1 日其他:- 键1:值1- 键2:值2---emp_name:酒吧雇员年龄:21出生日期:1996 年 1 月 1 日其他:- 键1:值1- 键2:值2...
我有以上四组值.我正在尝试将所有员工姓名保存在一个数组中,但我无法获得它.
使用 Dumper
我只能将第一部分(John 的)文件打印为 JSON.我无法获取单个值(例如,获取数组中的所有员工姓名).
使用严格;使用警告;使用 YAML::XS 'LoadFile';使用 Data::Dumper;我的 $config = LoadFile('input2.yml');打印转储器($config), '
';打印预期输出:
";打印约翰
Doe
foo
Bar
";print "--- 实际输出 --";我的 $empName;for(我的 $i=0;$i<4;$i++){$empName = $config->[$i]->{emp_name};}
有什么帮助吗?
以上是代码.我想获取员工姓名列表,但出现错误:
在 yamlParser.pl 第 15 行不是 ARRAY 引用
提供的 yaml 提供了 4 个文档,而不是 4 个项目的数组,所以你只需要取消引用这些.阅读文档:perldoc YAML::XSp>
变化:
我的 $config = LoadFile('input2.yml');
收件人:
我的@conf = LoadFile('input2.yml');我的 $config = @conf;
I am trying to get data from a YAML file for my Perl script.
Following is a similar sample scenario:
Let us consider a YAML file for employee data.
---
emp_name: John
emp_age: 27
DOB: 1/1/1990
others:
- key1: value1
- key2: value2
---
emp_name: Doe
emp_age: 25
DOB: 1/1/1992
others:
- key1: value1
- key2: value2
---
emp_name: foo
emp_age: 22
DOB: 1/1/1995
others:
- key1: value1
- key2: value2
---
emp_name: Bar
emp_age: 21
DOB: 1/1/1996
others:
- key1: value1
- key2: value2
...
I have the above four set of values. I'm trying to get all employee names saved in an array, but I'm unable to get it.
With Dumper
I am able to print only the first section (John's) file as a JSON. I'm not able to get individual values (eg. get all employee name in an array).
use strict;
use warnings;
use YAML::XS 'LoadFile';
use Data::Dumper;
my $config = LoadFile('input2.yml');
print Dumper($config), '
';
print "Expected output:
";
print "John
Doe
foo
Bar
";
print "--- Actual Output --";
my $empName;
for(my $i=0; $i<4; $i++)
{
$empName = $config->[$i]->{emp_name};
}
Any help?
The above is the code. I would like to fetch list of employee names, but I get an error:
The yaml presented offers 4 documents, not an array of 4 items, so you just need to dereference those. Have a read of the docs:perldoc YAML::XS
Change:
my $config = LoadFile('input2.yml');
To:
my @conf = LoadFile('input2.yml');
my $config = @conf;
这篇关于解析包含多个文档的 YAML 并访问对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!