简体   繁体   English

在 perl 中将哈希推入数组,结果无法理解

[英]push hash onto array in perl, result defies understanding

Why does this..为什么这..

my @menu;

my %el1 = ("element1" => "hello");
push @menu, \%el1;

my %el2 = ("element2" => "world");
push @menu, \%el2;

print to_json({"menu", @menu});

produce this..生产这个..

{
    "menu": {
        "element1": "hello"
    },
    "HASH(0x18e2280)": null
}

and not this..而不是这个..

{
    "menu": {
        "element1": "hello",
        "element2": "world"
    }
}

You have pushed two hash references onto @menu .您已将两个哈希引用推送到@menu So when you run this code:所以当你运行这段代码时:

print to_json({"menu", @menu});

It's exactly as if you ran:就好像你跑了一样:

print to_json({ "menu", \%el1, \%el2 });

The bit between { ... } is interpreted as a hash so the first and third items are seen as hash keys and the second item is seen as a value. { ... }之间的位被解释为散列,因此第一项和第三项被视为散列键,第二项被视为值。 So you get the output that you see.所以你会得到你看到的输出。 (And, as has been pointed out in comments, you would get a warning under use warnings as that second key has no associated value). (并且,正如评论中指出的那样,您会在use warningsuse warnings ,因为第二个键没有关联的值)。

I think that what you wanted to write was:我认为你想写的是:

print to_json({ "menu", \@menu });

But even that isn't right.但即使这样也不对。 You get the following:您将获得以下信息:

{
    "menu":[{
        "element1":"hello"
    },{
        "element2":"world"
    }]
}

The two hashes that you added to the array are still quite separate.您添加到数组中的两个散列仍然是完全独立的。

But what you actually want is a single hash.但你真正想要的是一个单一的哈希。 So create that instead.所以创建它。

#!/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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM