【问题标题】:Perl: Convert array of keys and values into a hashPerl:将键和值数组转换为哈希
【发布时间】:2014-07-23 14:00:17
【问题描述】:

我有两个这样的数组

my @keys = qw/Key_1 Key_2 Key_3/;
my @values = qw/foo bar more/;

有没有一种捷径(即单个函数)可以在不使用循环的情况下获得这样的哈希?

my %hash_table = ( Key_1 => "foo", Key_2 => "bar", Key_3 => "more" );

我尝试使用map函数但没有成功。

【问题讨论】:

    标签: arrays perl hash


    【解决方案1】:

    使用哈希slice

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

    使用地图,

    my %hash_table = map { $keys[$_] => $values[$_] } 0 .. $#keys;
    

    【讨论】:

      猜你喜欢
      • 2011-02-23
      • 1970-01-01
      • 2015-04-19
      • 2010-10-18
      • 1970-01-01
      • 2012-07-15
      • 2019-10-27
      • 2019-05-23
      • 2015-01-09
      相关资源
      最近更新 更多