perl - 如何循环访问 hashref?

perl - How to loop access hashref?

我有一些 hashref 格式的数据。我从 graph.facebook.com 获取数据 如何循环访问?

$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 $m ($var->{data})
{
    if ( $m->{name} =~ /Timeline/i )
    {
        print "id = $m->{id}\n";
    }
}

您需要取消引用数组 (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