使用map创建数组中出现的哈希



我似乎记得有一个;聪明的";使用带有map的Perl从数组创建哈希的方法,使得键是数组的元素,值是元素出现的次数。类似的东西,尽管这不起作用:

$ perl -e '@a = ('a','a','b','c'); %h = map { $_ => $_ + 1  } @a ; foreach $k (keys (%h)) { print "$k -> $h{$k}n"}'
c -> 1
b -> 1
a -> 2
$

我在想象吗?我该怎么做?

您可以在编写map {$h{$_}++} @a时忽略其返回值,但为什么要这样做呢?for (@a){$h{$_}++}很容易打字。

那么,为什么你去做呢?

map用于转换列表。它获取一个输入列表并生成一个输出列表。如果你以不同的方式使用它,使用副作用而不是输出,它可能会让读者感到困惑。

此外,尽管map经过优化,在void上下文中调用时不会创建输出列表,但速度较慢:

use warnings;
use strict;
use Benchmark qw/cmpthese/;
my @in = map {chr(int(rand(127)+1))} 1..10000;
my %out;
cmpthese(10000,
{stmtfor => sub{%out = (); $out{$_}++ for @in},
voidmap => sub{%out = (); map {$out{$_}++} @in;},
}
);
__END__
Rate voidmap stmtfor
voidmap 2075/s      --    -17%
stmtfor 2513/s     21%      --

我不确定这是您想要的,但使用for而不是map:可以很容易地做到这一点

$ perl -e '@a = ('a','a','b','c'); $h{$_}++ for @a; foreach $k (keys (%h)) { print "$k -> $h{$k}n"}'
c -> 1
b -> 1
a -> 2

最新更新