T J
T J

Reputation: 19

Can I use the contents of an array as the keys of a hash?

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

Answers (4)

ikegami
ikegami

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

daxim
daxim

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

geekosaur
geekosaur

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

  1. you need a second pass to actually account for the words in the line;
  2. you can't cheat and change the 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

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

my %word_count = map { $_ => 0 } split(" ", $line);

Upvotes: 0

Related Questions