2014-09-26 48 views
0

我有這樣一個JSON文件(它是一塊整個JSON文件的):解碼JSON在Perl

{ 
    id => "mgp1310", 
    samples => [ 
    { 
     envPackage => { 
     data => { 
      diss_carb_dioxide => { 
      aliases => ["sediment_diss_carb_dioxide"], 
      definition => "concentration of dissolved carbon dioxide", 
      mixs  => 1, 
      required => 0, 
      type  => "text", 
      unit  => "", 
      value  => "17 mM", 
      }, 
     }, 
     id => "mge64559", 
     }, 
    }, 
    ], 
} 

這已經通過模塊JSON解碼,使用:

use Data::Dumper; 
use JSON; 

open($fh, '<', 'hola.txt'); 
$json_text = <$fh>; 
$perl = decode_json($json_text); 
print Dumper($perl); 

現在我知道$perl有一個散列。所以我想用print $perl{"id"};打印JSON文件的id。但是,它不打印什麼,我不知道爲什麼。

+5

'嚴格使用;'再試一次。 – 2014-09-26 10:47:51

+4

從來沒有這麼簡單是如此有用...... – user2979409 2014-09-26 10:53:06

+1

'使用警告;'也是真正有用的。 – 2014-09-27 02:42:57

回答

5

我找到了答案,在我的代碼中添加了use strict。它扔了以下錯誤:

Global symbol "%perl" requires explicit package name at json.pl line 12. 

變量$perl是一個標量,而不是一個哈希!當然......我沒有想過這件事。所以我不能訪問散列寫作$perl{"id"}。正確的方法是$perl->{id}