title: Store line number and number of occurances per word using hash perl
body: <p>I am reading in a file word by word (where a file contains lines of words) and storing each word in to a hash.  I would like to store the number of occurrences as well as which line the word was found on (note:  I will be sorting the hash based on the words themselves, as shown in the code)</p>
  
  <p>I have (unworking) (assume that the words-array has word stored correctly, with no special characters, and is lowercase):</p>
  
  <pre><code>my %wordlist;
  my $line = 0;
  
  foreach my $word (@words) {
    $line++;
  
    if (exists $wordlist{$word}) {
        $wordlist{$word} += 1;
        $wordlist{$line} = $wordlist{$line} . ", $line";
    }
    else {
        $wordlist{$word} = 1;
        $wordlist{$line} = "$line";
    }  
  }
  </code></pre>
  
  <p>And later I try to print $wordlist{$line} as a string, inside a loop containing:</p>
  
  <pre><code>printf "%${length}s: %4d times, on lines %s\n", $key, $wordlist{$key}, $wordlist{$line};
  </code></pre>
  
  <p>When running, I get the error:</p>
  
  <pre><code>Use of uninitialized value in printf at ./wc.pl line 105, &lt;FILE&gt; line 20.
  someWord:    2 time(s), line(s) 
  </code></pre>
  
  <p>where line 20 is the exit statement</p>