如何从两个列表(键和值)声明和初始化哈希?

时间:2017-07-20 13:58:29

标签: perl

我似乎记得最近看到一些语法让你做这样的事情

my %hash; @hash{@keys} = @values;

在一份声明中。我试过了明显的

my %hash{@keys} = @values;

但是这产生了语法错误。我只是在做梦,还是有新的语法?

2 个答案:

答案 0 :(得分:1)

my %hash = map +($keys[$_] => $values[$_]), 0 .. $#keys;

或者,您可以使用List::MoreUtils::zip,但我怀疑@hash{@keys} = @values会更有效率。

#!/usr/bin/env perl

use strict;
use warnings;

my @keys = ('a' .. 'z');
my @values = map ord, @keys;

my %map = map +($keys[$_] => $values[$_]), 0 .. $#keys;

use YAML::XS;
print Dump \%map;

答案 1 :(得分:0)

这是另一种方法......

#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
use List::MoreUtils qw(zip); # Here is another way to make a hash. 
# If you forgot how to install the module if it didn't come with your system perl, it's easy ...
# cpan install List::MoreUtils 
# Do that in your terminal. 

# I decided to reverse the letters and the numbers so I could show you how to sort it the hash. 
my @letters = reverse('A' .. 'Z');
my @numbers = reverse(1 .. 26);
my %Hash;

# You can make a hash like this from arrays of equal sizes. 
@Hash{@letters} = @numbers; 

say "\n Here is the hash formed standardly";
foreach(sort{$a cmp $b} keys %Hash)
{
    say "$_ => $Hash{$_}";
}

%Hash = zip(@letters, @numbers);
say "\nHere is the hash formed using the zip function";
foreach(sort{$a cmp $b} keys %Hash)
{
    say "$_ => $Hash{$_}";
}