4

我正在遍历指向经度/城市的键/值对的纬度键哈希值的缓存。我正在尝试找到与已经查找的内容足够接近并且在散列中的纬度/经度的近似匹配。

我正在这样做

    foreach my $lat_key ( keys $lookup_cache_latlonhash ) {

        if ( ($lat > ($lat_key - .5)) && ($lat < ($lat_key + .5)) ) {

            foreach my $lon_key ( keys %{ $lookup_cache_latlonhash->{$lat_key}} ) {

                if ( ($lon > ($lon_key - .5)) && ($lon < ($lon_key + .5)) ) {

                    $country = $$lookup_cache_latlonhash{$lat_key}{$lon_key};
                    print "Approx match found: $lat_key $lon_key $country\n";
                    return $country;
                }
            }
        }
    }

该代码用于在该范围内查找这些纬度/经度对。但是,对于它循环使用的每个纬度,当它确实发现它在范围内(第一个嵌套条件)时,它会将其添加到keys %{ $goog_lookup_cache_latlonhash->{$lat_key}}不打算使用的哈希(大概是 )中,向哈希添加无用/空键:

$VAR1 = {
      '37.59' => {},
      '37.84' => {},
      '37.86' => {},
      '37.42' => {
                   '126.44' => 'South Korea/Jung-gu'
                 },
      '37.92' => {},
      '37.81' => {},
      '38.06' => {
                   '-122.53' => 'America/Novato'
                 },
      '37.8' => {},
      '37.99' => {},
      '37.61' => {},
       ...

进行此查找的聪明或至少理智的方法是什么?所以我不会只是通过查找它们无意中将键添加到哈希中?

4

3 回答 3

9

你正在经历的是自动复活。Perl 的一个特性是让使用嵌套结构更容易一些。

任何时候取消引用未定义的值,perl 都会自动创建您正在访问的对象。

use Data::Dumper; 
my $hash = {}; if ($hash->{'a'}) {} #No auto-vivification because you're just checking the value   
keys %{$hash->{'b'}}; #auto-vivification because you're acting on the value (getting the keys of it) $hash->{b} 
print Dumper($hash);

有几种方法可以避免这种情况 -

  1. 添加no autovivification要避免此功能的范围
  2. 检查您正在访问的项目是否已定义或存在(并且是您需要的类型)

我推荐第二个,因为它有助于养成检查代码是否正确数据结构的习惯,并使调试更加容易。

foreach my $lat_key (keys $lookup_cache_latlonhash) {
    if (($lat > ($lat_key - .5)) 
        && ($lat < ($lat_key + .5)) 
        && ref($lookup_cache_latlonhash->{$lat_key}) eq 'HASH')  #expecting a hash here - undefined or any non-hash value will skip the foreach
    {
        foreach my $lon_key (keys %{ $lookup_cache_latlonhash->{$lat_key}}) {
            if (($lon > ($lon_key - .5)) && ($lon < ($lon_key + .5))) {
                $country = $$lookup_cache_latlonhash{$lat_key}{$lon_key};
                print "Approx match found: $lat_key $lon_key $country\n";
                return $country;
            }
        }
    }
}
于 2018-09-14T04:56:34.837 回答
2

no autovivification;

在适用范围。

于 2018-09-14T04:51:40.183 回答
2

您可以为此使用exists 关键字

解决方案

use Data::Dumper;
$hash = {};
$hash{'alpha'} = 'yep';
$hash{'beta'} = 'this too';
if (exists $hash{'gamma'}) {
    print "Found gamma."
}
print Dumper(\%hash);
$hash{'gamma'} = 'added';
if (exists $hash{'gamma'}) {
    print "Gamma was updated.\n"
}
print Dumper(\%hash);

示例输出

$VAR1 = {
          'beta' => 'this too',
          'alpha' => 'yep'
        };
Gamma was updated.
$VAR1 = {
          'gamma' => 'added',
          'beta' => 'this too',
          'alpha' => 'yep'
        };
于 2018-09-14T04:52:17.327 回答