2013-10-24 98 views
0

假設Geo::Coder::Google數據轉儲的這種結構--- dd $location;如何訪問Perl結構中某個鍵的特定值?

address_components => [ 
    { 
     long_name => "Blackheath Avenue", 
     short_name => "Blackheath Ave", 
     types => ["route"], 
    }, 
    { 
     long_name => "Greater London", 
     short_name => "Gt Lon", 
     types => ["administrative_area_level_2", "political"], 
    }, 
    { 
     long_name => "United Kingdom", 
     short_name => "GB", 
     types => ["country", "political"], 
    }, 
    { 
     long_name => "SE10 8XJ", 
     short_name => "SE10 8XJ", 
     types => ["postal_code"], 
    }, 
    { long_name => "London", short_name => "London", types => ["postal_town"] }, 
    ], 
    formatted_address => "Blackheath Avenue, London SE10 8XJ, UK", 
    geometry => { 
    bounds  => { 
     northeast => { lat => 51.4770228, lng => 0.0005404 }, 
     southwest => { lat => 51.4762273, lng => -0.0001147 }, 
    }, 
    location  => { lat => 51.4766277, lng => 0.0002212 }, 
    location_type => "APPROXIMATE", 
    viewport  => { 
     northeast => { lat => 51.4779740302915, lng => 0.00156183029150203 }, 
     southwest => { lat => 51.4752760697085, lng => -0.00113613029150203 }, 
    }, 
    }, 
    types => ["route"], 
} 

一個例子電話:

my $long_name = &get_field_for_location("long_name", $location); 

繼子返回第一個long_name(在這個例子---類型=路線):

sub get_field_for_location($$) { 
    my $field = shift; 
    my $location = shift; 

    my $address = $location->{address_components}; 
    return $_->{$field} for @$address; 
} 

如何訪問的另一個long_name類型?即如何修改此子項以訪問給定類型條目的$field

+1

我不明白這個問題。 – simbabque

+0

這不是我打算只得到第一個條目。爲了節省時間,我問如何應對這種結構。 – mnemonic

回答

2

它應該返回第一political類型的,

my $type = "political"; 

my ($first_of_type) = grep { 
    grep { $_ eq $type } @{$_->{types}}; 
} @$address; 

return $first_of_type->{$field}; 

@$address陣列的grep濾波器元件,以及內grep濾波器types元素,即。 ["administrative_area_level_2", "political"]

3

types是對字符串數組的引用。您需要檢查它們中的任何一個是否符合所需的類型。您可以使用List::Util::first

use List::Util qw(first); 

sub get_field_for_location { 
    my $field = shift; 
    my $location = shift; 
    my $type = shift; 

    my $address = $location->{'address_components'}; 
    for my $component (@{$address}) { 
     if (first { $_ eq $type } @{$component->{'types'}}) { 
      return $component->{$field}; 
     } 
    } 
} 
+0

+1它工作時添加\t my $ address = $ location - > {address_components}; ---對不起 - 只能標記1個答案 – mnemonic