Reputation: 19
I want my array to become the keys of my new hash. I am writing a program that counts the number of word occurrences in a document.
my @array = split(" ", $line);
keys my %word_count = @array; #This does nothing
This segment is occuring while I am reading the infile line by line. I am trying to find a way to complete this project using hashes. The words are the keys, and the number of times they appear are the values. But, this step in particular is puzzling me.
Upvotes: 2
Views: 74
Reputation: 385819
You're trying to count the number of occurences of words in a line, right? If so, you want
my %word_count;
++$word_count for split(/\s+/, $line);
Or to put it on its head in order to facilitate refining the definition of a word:
my %word_count;
++$word_count for $line =~ /(\S+)/g;
Upvotes: 0
Reputation: 39158
Use a hash slice.
my %word_count;
@word_count{split ' ', $line} = ();
# if you like wasting memory:
# my @array = split ' ', $line;
# @word_count{@array} = (0) x @array;
Upvotes: 5
Reputation: 61379
You can't do it that way, certainly.
my %word_count = map {($_, 0)} @array;
would initialize the keys of the hash; but generally in Perl you don't want to do that. Two issues here are that
0
to 1
above, because if a word is repeated in the line you will count it only once, the others being overwritten.Upvotes: 2