Home arrow Perl Programming arrow Page 5 - Hash Functions

Counting Things - Perl

In this second part of a two-part series on hashes in Perl, you'll learn about hash functions and hashes in different contexts. This article is excerpted from chapter five of the book Beginning Perl, written by James Lee (Apress; ISBN: 159059391X).

TABLE OF CONTENTS:
  1. Hash Functions
  2. Hash in Scalar Context
  3. Hash Functions
  4. Hash Examples
  5. Counting Things
By: Apress Publishing
Rating: starstarstarstarstar / 1
May 06, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

A very common use of a hash variable is to count things. For instance, we can count the number of characters in a string or the items in an array. Let’s look at counting items in an array.

We will create an array of names and then we will count the number of times each name occurs in the array. For instance, for this array:

my @names = qw(
    John   Sue    Larry
    Mary   John   Mary
    Larry  John   Joe
    Lisa   John   Mary
);

we see that@namesis a collection of 12 names. Upon close inspection, we see that “John” occurs four times, “Sue” occurs once, and so on.

We can use a hash to keep a count of the number of times a name occurs in@namesby creating a hash that will have the names as its keys, and the number of occurrences of the name as the value associated with the key. For instance, when all the names in@namesare processed, we will end up with a hash that resembles

John  => 4,
Sue   => 1,
Larry => 2,
Mary  => 3,
Joe   => 1,
Lisa  => 1

Here is a program illustrating this concept:

#!/usr/bin/perl -w
# count.pl

use strict;

my @names = qw(
    John   Sue    Larry
    Mary   John   Mary
    Larry  John   Joe
   
Lisa   John   Mary
);

my %count;

foreach (@names) {
    if (exists $count{$_}) {
        $count{$_}++;
    } else {
        $count{$_} = 1;
    }
}

foreach (keys %count) {
    print "$_ \toccurs $count{$_} time(s)\n";
}

Executing this code produces the following result:

$ perl count.pl
Joe      occurs 1 time(s)
Lisa     occurs 1 time(s)
John     occurs 4 time(s)
Mary     occurs 3 time(s)
Sue      occurs 1 time(s)
Larry    occurs 2 time(s)
$

The most important part of this program is when we loop through the array and keep count:

foreach (@names) {
    if (exists $count{$_}) {
        $count{$_}++;
    } else {
        $count{$_} = 1;
    }
}

This code implements the logic “For each name in the array, if the name already exists in the hash, then increment the value by 1 (incrementing the count); else if it does not exist in the hash, then add the name to the hash with the initial value of 1.” After all the names are processed, then the hash will contain all the names and the number of times that each name is present in@names.

For minimalists, theifstatement can be shortened because this logic:

if (exists $count{$_}) {
    $count{$_}++;
} else {
    $count{$_} = 1;
}

is built into the statement

$count{$_}++;

Therefore, ourforeachloop could be changed to

foreach (@names) {
    $count{$_}++;
}

or more simply

$count{$_}++ foreach @names;

Summary

Hashes are unordered structures made up of pairs, each pair consisting of a key and a value, and given the key we can look up the value. Generally,
$hash{$key} = $value. We can loop over all the elements of a hash by processing the keys using aforeachloop to go through the keys.

Hashes are very useful variables that allow us to create data that is human-readable, reversible, and often used for counting things.

Exercises

  1. Create this hash variable:

    scalar => 'dollar sign',
    array  => 'at sign',
    hash   => 'percent sign'

    Process it with aforeachloop that prints the key/value pairs so that the keys are printed in sorted order:

    array: at sign
    hash: percent sign
    scalar: dollar sign

  2. Store your important phone numbers in a hash. Write a program to look up numbers by the person’s name.
  3. Turn the joke machine program in Chapter 4 from two arrays into one hash. While doing so, write some better lightbulb jokes.

 

 



 
 
>>> More Perl Programming Articles          >>> More By Apress Publishing
 

blog comments powered by Disqus
   

PERL PROGRAMMING ARTICLES

- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates

 



© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap

Dev Shed Tutorial Topics: