如何在Perl结构中访问键的特定值? [英] how to access a specific value of a key within a Perl structure?
本文介绍了如何在Perl结构中访问键的特定值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假定Geo::Coder::Google
数据转储的这种结构--- dd $location;
.
Assume this structure of a Geo::Coder::Google
data dump --- dd $location;
.
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);
随后的sub返回第一个long_name
(在本示例中为--type = route):
Following sub returns the first long_name
(in this example --- type=route):
sub get_field_for_location($$) {
my $field = shift;
my $location = shift;
my $address = $location->{address_components};
return $_->{$field} for @$address;
}
如何访问其他类型的long_name
?即如何修改此子项以访问给定类型条目的$field
?
How to access a long_name
of another type? i.e. how to modify this sub to access a $field
for a given type entry?
推荐答案
它应首先返回类型为political
,
my $type = "political";
my ($first_of_type) = grep {
grep { $_ eq $type } @{$_->{types}};
} @$address;
return $first_of_type->{$field};
外部grep
过滤@$address
数组的元素,内部grep
过滤types
数组的元素,即. ["administrative_area_level_2", "political"]
Outer grep
filters elements of @$address
array, and inner grep
filters elements of types
, ie. ["administrative_area_level_2", "political"]
这篇关于如何在Perl结构中访问键的特定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文