Perl将数组元素放入哈希



我有一个带有一堆字符串作为元素的数组,我想将其放入哈希。因此,我首先将字符串洒在阵列中,然后将解析的字符串放入一个新数组调用parse_list中。

这是我的代码:

#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use Data::Dumper qw(Dumper);
my %hash;
my $string_array = [
                "Europe West France Spain Germany",
                "Europe North Finland Iceland",
                "Asia East Japan Korea China",
                "America North Mexico USA Canada"
    ];
foreach my $country(@{$string_array}){ 
    my @parse_list = split(/s+/, $country);
    (my $continent,my $region,) = @parse_list[0,1];
    #I just know how to get the continent and region, I don't know how to put       
    #the element from index [2..4] to an array 
}

我如何设置

大陆作为主键, region 作为哈希的第一层中的值。

region 作为辅助键,数组 country 作为哈希的第二层中的值。

所以就像

my %hash = (
    Europe => {
        West => [ "France", "Spain", "Germany"]
        }
    );

当您"解析"列表时,将所有内容存储在单个数组中不是很有帮助。相反,将数据放入更有用的变量中。

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my $string_array = [
  "Europe West France Spain Germany",
  "Europe North Finland Iceland",
  "Asia East Japan Korea China",
  "America North Mexico USA Canada"
];
my %geography;
for (@$string_array) {
  my ($continent, $region, @countries) = split;
  $geography{$continent}{$region} = @countries;
}
print Dumper %geography;

输出为:

$VAR1 = {
          'America' => {
                         'North' => [
                                      'Mexico',
                                      'USA',
                                      'Canada'
                                    ]
                       },
          'Europe' => {
                        'West' => [
                                    'France',
                                    'Spain',
                                    'Germany'
                                  ],
                        'North' => [
                                     'Finland',
                                     'Iceland'
                                   ]
                      },
          'Asia' => {
                      'East' => [
                                  'Japan',
                                  'Korea',
                                  'China'
                                ]
                    }
        };

update (添加更多说明):

我已经将%hash的名称更改为%geography-命名变量非常重要。

使用for (...)构造时,使用Perl的默认行为并将列表元素存储在$_中通常很有用。这是因为$_通常是各种操作的默认输入变量。例如,在这种情况下,我本可以写的:

for my $geo (@$string_array) {
  my ($continent, $region, @countries) = split /s+/, $geo;
  ...
}

但是split函数默认情况下在$_上起作用。而且,更好的是,它的标准行为是在/s+/上分开,因此我们也可以忽略所有这些,并最终得到很多更干净的代码:

for (@$string_array) {
  my ($continent, $region, @countries) = split;
  ...
}

最新更新