我正在尝试修改现有的perl脚本以支持地理编码。 找到了这个模块:http://metacpan.org/pod/Geo::Coder::Google
我无法弄清楚如何从它返回的哈希结构中提取数据(我不是perl编码器,这只是我必须解决的一些遗留脚本)。
{
'AddressDetails' => {
'Country' => {
'AdministrativeArea' => {
'SubAdministrativeArea' => {
'SubAdministrativeAreaName' => 'San Francisco',
'Locality' => {
'PostalCode' => {
'PostalCodeNumber' => '94107'
},
'LocalityName' => 'San Francisco',
'Thoroughfare' => {
'ThoroughfareName' => '548 4th St'
}
}
},
'AdministrativeAreaName' => 'CA'
},
'CountryNameCode' => 'US'
}
},
'address' => '548 4th St, San Francisco, CA 94107, USA',
'Point' => {
'coordinates' => [
'-122.397323',
'37.778993',
0
]
}
}
尝试了我在google上找到的所有哈希教程,我能打印的最多就是HASH(0x91e5558)。到目前为止,我的代码就是模块显示的例子:
use Geo::Coder::Google;
my $geocoder = Geo::Coder::Google->new(apikey => 'Your API Key');
my $location = $geocoder->geocode( location => 'Hollywood and Highland, Los Angeles, CA');
我只想要点 - >将数据协调到它自己的变量,然后我可以写入数据库。
答案 0 :(得分:5)
这是你想要的吗?
$lon = $location->{Point}{coordinates}[0];
$lat = $location->{Point}{coordinates}[1];
答案 1 :(得分:2)
我只想提出一个更容易编码的OO版本。由于Tatsuhiko没有提供它,我想证明它有可能
所以这是包定义。
package Geo::Coder::Google::Geocode;
use strict;
use warnings;
use Carp qw<croak>;
use Params::Util qw<_ARRAY _CLASS _CLASSISA _HASH _INSTANCE>;
sub new {
croak( 'Not a valid subclass' )
unless my $class = _SUBCLASS( _CLASS( $_[0] ), __PACKAGE__ )
;
croak( 'Not a valid structure!' )
unless my $struct = _HASH( $_[1] )
and _HASH( $_[0]->{Point} )
;
# Done with checks, just bless it
return bless( $struct, $class );
}
sub coordinates {
my ( $self, $point, $coords ) = shift;
# Make sure each link in the chain exists ( and is populated ).
return unless _INSTANCE( $self, __PACKAGE__ )
and $point = _HASH( $self->{Point} )
and $coords = _ARRAY( $point->{coordinates} )
;
We have an array ref here, return it.
return wantarray ? @$coords : $coords;
}
{ package Geo::Coder::Google;
use Carp qw<croak>;
use Params::Util qw<_HASH>;
sub get_geocode {
croak( 'Geocode not created!' ) unless my $gcode = _HASH( &geocode );
return Geo::Coder::Google::Geocode->new( $gcode );
}
}
然后,您可以这样使用它:
my ( $lat, $long )
= $geocoder->get_geocode(
location => 'Hollywood and Highland, Los Angeles, CA'
)->coordinates
;
这将创建一个快速封装,以便将来更容易编写访问,并提供对使用代码的简单更改。
你也可以添加这个功能:
{ package Geo::Coder::Google;
use Carp qw<croak>;
use Params::Util qw<_HASH>;
sub get_coordinates {
croak( 'Geocode not created!' ) unless my $gcode = _HASH( &geocode );
return Geo::Coder::Google::Geocode->new( $gcode )->coordinates;
}
}
然后致电:
my ( $lat, $long )
= $geocoder->get_coordinates( location => 'Hollywood and Highland, Los Angeles, CA' )
;
答案 2 :(得分:0)
你正在寻找这样的东西:
$hashref = {
'a' => 'A',
'b' => {
'c' => 'C',
'some' => 'value',
},
};
print "$hashref->{b}{some}\n"; # output: value