perlforeachhashref

How to loop access hashref?


I have some data in a hashref format. I fetch the data from graph.facebook.com. How can I access the data in the hash with a loop?

$var = \{
            'data' => [
                        {
                          'id' => '312351465029_10154168935475030',
                          'name' => 'Timeline Photos 1'
                        },
                        {
                          'name' => 'Bangchak\'s cover photo',
                          'id' => '312351465029_10154168087455030',
                        },
                        {
                          'id' => '312351465029_10154168081875030',
                          'name' => 'Timeline Photos 2',
                        }
                      ],
            'paging' => {
                          'previous' => 'https://graph.facebook.com/v2.6/312351465029/2',
                          'next' => 'https://graph.facebook.com/v2.6/312351465029/3'
                        }
          };

This code didn't work:

foreach $m ($var->{data})
{
    if ( $m->{name} =~ /Timeline/i )
    {
        print "id = $m->{id}\n";
    }
}

Solution

  • You need to dereference the array (perldoc perldsc):

    use warnings;
    use strict;
    
    my $var = {
                'data' => [
                            {
                              'id' => '312351465029_10154168935475030',
                              'name' => 'Timeline Photos 1'
                            },
                            {
                              'name' => 'Bangchak\'s cover photo',
                              'id' => '312351465029_10154168087455030',
                            },
                            {
                              'id' => '312351465029_10154168081875030',
                              'name' => 'Timeline Photos 2',
                            }
                          ],
                'paging' => {
                              'previous' => 'https://graph.facebook.com/v2.6/312351465029/2',
                              'next' => 'https://graph.facebook.com/v2.6/312351465029/3'
                            }
              };
    
    foreach my $m (@{ $var->{data} }) {
        if ( $m->{name} =~ /Timeline/i )
        {
            print "id = $m->{id}\n";
        }
    }
    
    __END__
    
    id = 312351465029_10154168935475030
    id = 312351465029_10154168081875030