开发者

How do I iterate over an array in a nested data structure?

I am attempting to parse over the MediaWiki's API output with format=yaml. My YAML code looks something like:

use YAML qw(Dump Bless Load);
use YAML::LoadURI;
use YAML::Tag;
my $yaml_hash = LoadURI($wiki_url);
my $id = $yaml_hash->{query}->{namespaces}->[0];
print $id;

This is fine and dandy, but how do you to iterat开发者_如何学JAVAe over the YAML output without brute forcing it? This would be idea, but obviously this does not work.

my $id = $yaml_hash->{query}->{namespaces}-[*]->{id}

This is what the YAML output looks like:

---
query:
  namespaces:
    -
      id: -2
      case: first-letter
      '*': Media
      canonical: Media
    -
      id: -1
      case: first-letter
      '*': Special
      canonical: Special
    -
      id: 0
      case: first-letter
      '*':
          content:
    -
      id: 1
      case: first-letter
      '*': Talk
      subpages:
      canonical: Talk
    -
      id: 2
      case: first-letter
      '*': User
      subpages:
      canonical: User
    -
      id: 3
      case: first-letter
      '*': User talk
      subpages:
      canonical: User talk


Is this what you want? Note: I haven't tested it:

Goal: something "Like" $yaml_hash->{query}->{namespaces}-[*]->{id} -- except functional

Try this:

my @ids = map { $_->{id} } @{$yaml_hash->{query}->{namespaces}} ;

However, a for loop is probably clearer to a lot of people.

my @ids;
foreach my $ns ( @{$yaml_hash->{query}->{namespaces}} ){ push @ids, $ns->{id} }

Note I am proceeding on general perl data structure knowledge, not anything YAML specific.

It is assumed that 'query' and 'namespaces' are literals; if those are parameters then you need to brute force those with additional for-in or while loops. For iterating over hashes, look up keys() and each() in perldoc perlfunc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜