Home arrow Perl Programming arrow Page 4 - Hashes

Adding, Changing, and Removing Elements - Perl

Hashes in Perl aren't really that hard to understand; they're not that much harder than understanding how a phone book works. This article introduces you to hashes, what they do, and how to use them. It is excerpted from chapter five of the book Beginning Perl, written by James Lee (Apress; ISBN: 159059391X).

  1. Hashes
  2. Creating a Hash
  3. Working with Hash Values
  4. Adding, Changing, and Removing Elements
By: Apress Publishing
Rating: starstarstarstarstar / 3
April 29, 2010

print this article



Hash entries are very much like ordinary scalar variables, except that you need not declare an individual hash key before assigning to it or using it. We can add a new person to our hash just by assigning to their hash entry:

$where{Eva} = "Uxbridge";
print "Eva lives in $where{Eva}\n";

A new entry springs into existence, without any problems. We can also change the entries in a hash just by reassigning to them. Letís move people around a little:

$where{Eva}      = "Denver";
$where{Samantha} = "California";
$where{Lucy}     = "Tokyo";
$where{Gary}     = "Las Vegas";
$where{Ian}      = "Southampton";

print "Gary lives in $where{Gary}\n";

To remove an entry from a hash, you need to use thedelete()function, as we do in this little variant onhash.pl:

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

use strict;

my %where = (
        Gary     => "Dallas",
        Lucy     => "Exeter",
        Ian      => "Reading",
        Samantha => "Oregon"

delete $where{Lucy};
print "Lucy lives in $where{Lucy}\n";

You can see that here we delete Lucyís entry in
%wherebefore we access it, so executing this program should produce an error. Sure enough, we get

$ perl badhash.pl
Use of uninitialized value in concatenation (.) at badhash.pl line 14
Lucy lives in

Itís not that we havenít initialized poor Lucy, but rather that weíve decided to get rid of her.

Please check back for the conclusion to this article.

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

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- 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


Dev Shed Tutorial Topics: