Boontawee Home Boontawee Home - 5 months ago 14
Perl Question

perl - How to loop access hashref?

I have some data in hashref format. I fetch data from graph.facebook.com
How to loop access?

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


These code Didn't work.

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

Answer

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