perlhashref

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


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?


Solution

  • 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