【问题标题】:Perl how to access a value of nested hash without specific some middle keys (wildcard)Perl如何在没有特定中间键(通配符)的情况下访问嵌套哈希值
【发布时间】:2022-01-09 04:50:48
【问题描述】:

我正在尝试获取 facebook 移动帖子。

$VAR1 = {
    "mf_story_key" => "225164133113094",
    "page_id" => "102820022014173",
    "page_insights" => {
         "102820022014173" => {
             "actor_id" => "102820022014173",
             "page_id" => "102820022014173",
             "page_id_type" => "page",
             "post_context" => {
                  "publish_time" => "1641702174",
                  "story_name" => "EntStatusCreationStory"
             },
             "psn" => "EntStatusCreationStory",
             "role" => 1,
         }
    },
    "story_attachment_style" => "album",
};

$publish_time = $VAR1->{page_insights}{102820022014173}{post_context}{publish_time};

如果 102820022014173 是一个动态值,我如何访问没有具体的 publish_time 值?

【问题讨论】:

  • 使用keyseach?

标签: perl hashref


【解决方案1】:

您需要将 keys 获取到 page_insights 哈希,然后遍历它们。

use strict;
use warnings;
use 5.010;

my $post = {
    "mf_story_key" => "225164133113094",
    "page_id" => "102820022014173",
    "page_insights" => {
        "102820022014173" => {
            "actor_id" => "102820022014173",
            "page_id" => "102820022014173",
            "page_id_type" => "page",
            "post_context" => {
                "publish_time" => "1641702174",
                "story_name" => "EntStatusCreationStory"
            },
            "psn" => "EntStatusCreationStory",
            "role" => 1,
        }
    },
    "story_attachment_style" => "album",
};

my $insights = $post->{page_insights};

my @insight_ids = keys %{$insights};

for my $id ( @insight_ids ) {
    say "ID $id was published at ",
        $insights->{$id}{post_context}{publish_time};
}

给予

ID 102820022014173 was published at 1641702174

【讨论】:

    【解决方案2】:
    for my $page_insight ( values( %{ $VAR1->{page_insights} } ) ) {
       my $publish_time = $page_insight->{post_context}{publish_time};
    
       ...
    }
    

    如果总是只有一个元素,

    my $page_insight = ( values( %{ $VAR1->{page_insights} } )[0];
    my $publish_time = $page_insight->{post_context}{publish_time};
    ...
    

    (如果您愿意,可以将这两个语句组合起来。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-14
      • 2020-07-07
      • 2019-09-08
      • 2017-08-02
      • 2014-10-17
      • 1970-01-01
      • 2017-07-30
      • 1970-01-01
      相关资源
      最近更新 更多