0

有人可以帮我如何将包含空格分隔的单词的字符串转换为散列,其中散列键是字符串中的单词,散列值是散列中单词的出现次数?

谢谢

4

2 回答 2

7

像这样的东西?

use strict;
use warnings;
use Data::Dumper;

my $string = "foo bar baz foo bar foo bar quux";
my %count;
$count{$_}++ for split /\s+/, $string;

print Dumper( \%count );

输出:

$VAR1 = {
          'bar' => 3,
          'baz' => 1,
          'quux' => 1,
          'foo' => 3
        };
于 2013-05-22T17:24:55.167 回答
1
  $string = "do re me fa so la te do";

  for $word ( split " +", $string )
     {
     $word_count{$word}++;
     }

  for $word ( keys %word_count )
     {
     print "$word\t$word_count{$word}\n";
     }

我更喜欢“+”而不是“\s+”,因为后者会切掉所有空白。你特别提到了空格,所以我只想削减实际的空格。

于 2013-05-22T17:31:23.963 回答