我有一个 Linux 命令,它从 API 中获取一些 YAML 格式的数据。我正在寻找一种方法将该变量填充到哈希数组中。我正在尝试
YAML::Tiny
,我编写的代码块是:
use YAML::Tiny;
my $stuff = `unix command that returns as yaml output`
my $yaml = YAML::Tiny->new;
$yaml = YAML::Tiny->new->read_string->($stuff);
但是,使用此代码运行将会出错:
Can't use string ("") as a subroutine ref while "strict refs" in use
$stuff
变量看起来像:
Cluster1:
source_mount: /mnt/uploads
dir: /a /b
default: yes
destination_mount: /var/pub
Cluster2:
source_mount: /mnt/uploads
dir: /c /d /e
default: no
destination_mount: /var/pub
您不应该使用
new
两次,并且 ->
之后不应该有 read_string
(请参阅 POD 中的 YAML::Tiny)。变化:
$yaml = YAML::Tiny->new->read_string->($stuff);
至:
$yaml = YAML::Tiny->read_string($stuff);
这是一个完整的工作示例:
use warnings;
use strict;
use YAML::Tiny;
my $stuff = '
Cluster1:
source_mount: /mnt/uploads
dir: /a /b
default: yes
destination_mount: /var/pub
Cluster2:
source_mount: /mnt/uploads
dir: /c /d /e
default: no
destination_mount: /var/pub
';
my $yaml = YAML::Tiny->new();
$yaml = YAML::Tiny->read_string($stuff);
print $yaml->[0]->{Cluster2}->{dir}, "\n";
输出:
/c /d /e