[英]push hash onto array in perl, result defies understanding
為什么這..
my @menu;
my %el1 = ("element1" => "hello");
push @menu, \%el1;
my %el2 = ("element2" => "world");
push @menu, \%el2;
print to_json({"menu", @menu});
生產這個..
{
"menu": {
"element1": "hello"
},
"HASH(0x18e2280)": null
}
而不是這個..
{
"menu": {
"element1": "hello",
"element2": "world"
}
}
您已將兩個哈希引用推送到@menu
。 所以當你運行這段代碼時:
print to_json({"menu", @menu});
就好像你跑了一樣:
print to_json({ "menu", \%el1, \%el2 });
{ ... }
之間的位被解釋為散列,因此第一項和第三項被視為散列鍵,第二項被視為值。 所以你會得到你看到的輸出。 (並且,正如評論中指出的那樣,您會在use warnings
下use warnings
,因為第二個鍵沒有關聯的值)。
我認為你想寫的是:
print to_json({ "menu", \@menu });
但即使這樣也不對。 您將獲得以下信息:
{
"menu":[{
"element1":"hello"
},{
"element2":"world"
}]
}
您添加到數組中的兩個散列仍然是完全獨立的。
但你真正想要的是一個單一的哈希。 所以創建它。
#!/usr/bin/perl
use strict;
use warnings;
use JSON;
use Data::Dumper;
my @menu;
my %el1 = (
"element1" => "hello",
"element2" => "world",
);
print to_json({"menu", \%el1});
如果傳遞對數組的引用,結果會更清晰:
print to_json({"menu", \@menu});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.