2013-10-01 69 views
1

我正在尋找一些解析YAML文檔的幫助。具體而言,我不確定主機打印/訪問「卷」元素。任何幫助將不勝感激。提前致謝!用perl解析YAML文件。如何訪問和解析不同的yaml對象。

Perl代碼:

#!/usr/bin/perl 

use YAML::Tiny; 


# Open the config 
$yaml = YAML::Tiny->read('file.yml'); 

# Reading properties 
my $root = $yaml->[0]->{rootproperty}; 
my $one = $yaml->[0]->{physical_interfaces}->{e0a}; 
my $Foo = $yaml->[0]->{physical_interfaces}->{e0b}; 
print "$root\n"; 
print "$one\n"; 
print "$volume1\n"; 

我YAML文件看起來像這樣:file.yaml

--- 
    rootproperty: netapp1 
    is_netapp: Yes 
    netapp_mode: 7mode 
    is_metro_cluster: Yes 
    is_vseries: Yes 
    is_flexcache_origin: No 
    snapmirror: 
     enabled: Yes 
     destination: Yes 
     lag_threshold: 2300 
    physical_interfaces: 
     e0a: netapp1-e0 
     e0b: netapp1-e1 
     mgt: netapp1-mgt 
    volumes: 
     - volume: vol1 
     reserve: 50 
     sched: 6 42 0 
     - volume: vol2 
     reserve: 20 
     sched: 0 3 0 

回答

4

那麼你似乎有正確的想法了。以相同的方式如可以用

my $root = $yaml->[0]{rootproperty} 

訪問rootproperty字段可以用

my $volumes = $yaml->[0]{volumes} 

$volumes訪問volumes陣列是現在體積散列數組的引用。你可以打印這些出來,例如,使用

for my $vol (@$volumes) { 
    print $vol->{volume}, "\n"; 
    print $vol->{reserve}, "\n"; 
    print $vol->{sched}, "\n"; 
    print "\n"; 
} 

隨着你顯示數據,這將產生輸出

vol1 
50 
6 42 0 

vol2 
20 
0 3 0 
+0

感謝您的幫助鮑羅廷! –