All pastes #1682913 Raw Edit

instructor's solution

public text v1 · immutable
#1682913 ·published 2009-11-22 23:16 UTC
rendered paste body
 #!/usr/bin/perl

    # Make sure our variables are clean
    undef(@words);
    undef(@wordcounts);
    undef($current_word);
    
    while (defined($line = <>))
    {
        # Add these words to our list
        push(@wordlist, split(" ", $line));
    } 
    # Sort the list
    @wordlist = sort(@wordlist);

    #
    # Add missing code here: create @words and @wordcounts arrays
    #

    # Step through the current list of words
    foreach $word (@wordlist)
    {
        # Have we seen this word already?
        if ($current_word ne $word)
        {
            # No, add the new word to @words
            push(@words, $word);
            # and a new count (of 1) to @wordcounts
            push(@wordcounts, 1);
            # and keep track of the new word we're on
            $current_word = $word;
        }
        else
        {
            # Yes, just increment the wordcount at the end of that array
            $wordcounts[$#wordcounts]++;
        }
    }

    # Print out the results
    for ($i = 0; $i < @words; $i++)
    {
        print "$words[$i]: $wordcounts[$i]\n";
    }