【问题标题】:How do I declare and initialize a hash from two lists (keys and values)? [duplicate]如何从两个列表(键和值)声明和初始化哈希? [复制]
【发布时间】:2017-12-26 06:43:48
【问题描述】:

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

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

在一个声明中。我尝试了明显的

my %hash{@keys} = @values;

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

【问题讨论】:

  • 我倾向于以duplicate 的身份关闭它。
  • perl6 可能会这样做。

标签: perl


【解决方案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;

【讨论】:

  • 是的,我知道这些,我只是想我看到了一种新的语法(à la hash slices),它可以让你在没有像 map 或 zip 这样的额外表达式的情况下做同样的事情。
  • 你在想Key/Value Hash Slices吗?我没有用过它们。我不确定它们是否可以用来执行此操作。
  • 可能是这样,或者可能是 Perl 6 中的某些东西。我开始认为我想象了整个事情。我刚刚经历了最后四个 perldelta,我没有看到任何明显的内容。
  • 还有this
【解决方案2】:

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

#!/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{$_}";
}

【讨论】:

  • 那个反向没有任何用处。散列已经是随机顺序(未绑定的散列不能保持顺序)。此外,这些都不是新语法。
猜你喜欢
  • 2015-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-18
  • 2011-04-15
  • 2016-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多