O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A.4. Chapter 5

  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 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 one turns out to be zero plus one, or one. (Recall that undef looks ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required