"225164133113094", "page_id" => "102820022014173", "page_insights" => { "1028" /> "225164133113094", "page_id" => "102820022014173", "page_insights" => { "1028" /> "225164133113094", "page_id" => "102820022014173", "page_insights" => { "1028"/>

Perl how to access a value of nested hash without specific some middle keys (wildcard)

74 Views Asked by At

I trying to fetch the facebook mobile posts.

$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};

If 102820022014173 is a dynamic value, how do I access the publish_time value without specific it?

2

There are 2 best solutions below

0
Andy Lester On BEST ANSWER

You need to get the keys to the page_insights hash and then iterate through them.

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};
}

gives

ID 102820022014173 was published at 1641702174
0
ikegami On
for my $page_insight ( values( %{ $VAR1->{page_insights} } ) ) {
   my $publish_time = $page_insight->{post_context}{publish_time};

   ...
}

If there's always going to exactly one element,

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

(You can combine the two statements if you so desire.)