简体   繁体   English

如何从Perl中的数组引用中优雅地创建哈希?

[英]How can I elegantly create a hash from an array reference in Perl?

I am looking for a more elegant way to create a hash that contains the list I have read in from my configuration file. 我正在寻找一种更优雅的方式来创建一个哈希,其中包含我从配置文件中读取的列表。 Here is my code: 这是我的代码:

read_config($config_file => my %config);

my $extension_list_reference = $config{extensions}{ext};

my @ext;

# Store each item of the list into an array

for my $i ( 0 .. (@$extension_list_reference - 1) ) {
    $ext[$i] = $extension_list_reference->[$i];
}

# Create hash with the array elements as the keys

foreach my $entry (@ext) {
    $extensions{$entry} = "include";
 }   

Thanks. 谢谢。

my %hash = map { $_ => 'include' } @list;

Try using map: http://perldoc.perl.org/functions/map.html 尝试使用地图: http//perldoc.perl.org/functions/map.html

Here's what your new code should look like: 以下是您的新代码应如下所示:

my %extensions = map { $_ => "include" } @{ $config{extensions}{ext} };

If I understand your problem, this is how you do it in one line: 如果我理解你的问题,这就是你如何在一行中做到这一点:

@extensions{@$extension_list_reference} = ();

Note: each value of the hash is empty, but you still can check whether the key exists in the hash using function exists , like this: 注意:哈希的每一个值是空的,但你仍然可以检查是否使用功能存在 ,这样在散列中存在的关键:

if(exists $extensions{$some_key}) {...

PS If by some reason you really need those strings 'include' as values, you can have them, too: PS如果由于某种原因你真的需要这些字符串'include'作为值,你也可以拥有它们:

@extensions{@$extension_list_reference} = ('include') x @$extension_list_reference;

This way: 这条路:

read_config($config_file => my %config);
%extensions = map +($_ => "include"), @{$config{extensions}{ext}};

or this way: 或者这样:

read_config($config_file => my %config);
@extensions{@{$config{extensions}{ext}}} = ("include") x @{$config{extensions}{ext}};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM