1. Here is one way to do it:

    %map = qw(red apple green leaves blue ocean);
    print "A string please: "; chomp($some_string = <STDIN>);
    print "The value for $some_string is $map{$some_string}\n";

    The first line creates the hash, giving it the desired key-value pairs. The second line fetches a string, removing the pesky newline. The third line prints the entered value, and its mapped value.

    You can also create the hash through a series of separate assignments, like so:

    $map{'red'} = 'apple';
    $map{'green'} = 'leaves';
    $map{'blue'} = 'ocean';
  2. Here’s one way to do it:

    chomp(@words = <STDIN>); # read the words, minus newlines
    foreach $word (@words) {
      $count{$word} = $count{$word} + 1; # or $count{$word}++
    }
    foreach $word (keys %count) {
      print "$word was seen $count{$word} times\n";
    }

    The first line reads the lines into the @words array. Recall that this method will cause each line to end up as a separate element of the array, with the newline character still intact.

    The next four lines step through the array, setting $word equal to each line in turn. The newline is discarded with chomp(), and then the magic comes. Each word is used as a key into a hash. The value of the element selected by the key (the word) is a count of the number of times we’ve seen that word so far. Initially, there are no elements in the hash, so if the word wild is seen on the first line, we have $count{"wild"}, which is undef. The undef value plus 1 turns out to be plus 1, or one. (Recall that undef looks like a ...

Get Learning Perl on Win32 Systems now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.