Everything2
Near Matches
Ignore Exact
Full Text
Everything2

Perl: Hashes

created by mshumphr

(thing) by eric+ (5.5 y) (print)   ?   I like it! Tue Jun 20 2000 at 22:31:25

In perl, a hash is differentiated from other data types with the '%'-sign. A hash is essentially an array whose elements are named. This makes it easy to access any specific element given that name. In common perl parlance, the element's name is called the "key" and the element is called the "value".

As mshumphr demonstrates above, a hash element is accessed with the '$'. There are two basic forms to dereference the data:

$value = $hash{key}
$value = $hash->{key}

In older per documentation, Hashes used to be called "associative arrays".

For more information, see the perldata manpage.


(idea) by m_turner (1.5 y) (print)   ?   1 C! I like it! Sat Oct 13 2001 at 19:41:11

The hash is one of the three basic data types with in the perl language. In the simplest form, the hash is designated with the '%' sign (often used as the mod operator within C-like languages and thus a critical part of any hash implementation) and accessed with the curly braces: '{' and '}'.

# init
%foo = (
    'a' => 1,
    5   => 'qux'
  );

print $foo{'a'},"\n";
1
print $foo{5},"\n";
qux

Often called an 'associative array', the hash is used to associate one data type with some value. The key point with the hash is that this does not have to be ordinal or enumerated to access. Arrays must be indexed with numbers or objects that have a clear order to them - for example '0, 1, 2, ...'. It is impossible to index an array with real numbers or strings - how many real numbers are there between '3.1' and '3.2'? Or how many strings between 'accuse' and 'ace'? There is no clean, programmatic answer for these questions and thus the hash table is the best choice for using these objects as an index into the data structure.

With an array, to have two elements '1' and '1000', there needs to be storage allocated for all 1000 elements. The equivalent hash is much smaller (often two storage units with a bit of buffer for more if necessary). In this way, the hash can be used as a sparse array for when most of the elements are '0' or empty with a very few items spread out over vast distances.

Another common use for hashes is counting elements or identifying all of the unique items - such as the following snipit demonstrates:

%counter;
$words = "How much wood would a woodchuck chuck " . 
         "if a woodchuck could chuck wood";
foreach $word (split(/\s+/,$words))
{
  $counter{$word}++;
}
foreach $word (keys %counter)
{
  print "$word: $counter{$word}\n";
}

a: 2
wood: 2
would: 1
much: 1
chuck: 2
How: 1
could: 1
if: 1
woodchuck: 2

keys takes a hash (such as %counter) and returns a list (or array if you prefer to think that way) of the indexes to the hash. Another approach is the use of each which will iterate through the hash returning (key,value) pairs.

With perl5, the addition of references has both complicated and simplified the issues. First off, this allows for deeper data structures such as hashes of hashes and multi-dimensional arrays (which weren't supported cleanly prior to perl5). Secondly, it means that it is now much easier to pass a hash (and especially multiple hashes) to and from a subroutine. To make a reference, simply put a '\' before the name of the hash (or array, or even at times scalar). The resulting value is a scalar:

%foo = ('a' => 5, 'b' => 2);
$bar = \%foo;
Accessing a hash reference is slightly different than that of a hash, the '->' operator comes into play.
print $bar->{'a'},"\n";
5
While the '->' can be used to access individual items of the array, to use either keys or each the hash must be dereferenced. If this is a simple hash reference (like $bar above), just placing the % before it to have '%$bar' will allow the function to access the hash reference as a hash. For hashes within other data structures, is necessary to cleanly designate the entire structure:
%foo = ('a' => 5, 'b' => 2);
@bar;
$bar[0] = \%foo;
print keys %{$bar[0]};
a b
(First the hash was set up, then the array was defined, and array element of 0 was assigned the value of the hash reference. Lastly the array element of 0 was accessed, and this scalar value dereferenced into a hash which was processed by keys and then printed.)

printable version
chaos

hash associative array Perl 5 Pocket Reference: Data Types Perl
how to increase the size of an array How much wood would a woodchuck chuck if a woodchuck could chuck wood? Breast Display and Climate pass by value vs. pass by reference
wood unique String could
Designate If Reference much
real number ordinal implementation array
associate data Buffer Enumerate
Y'know, if you log in, you can write something here, or contact authors directly on the site. Create a New User if you don't already have an account.
  Epicenter
Login
Password

password reminder
register

Everything2 Help

Cool Staff Picks
The best nodes of all time:
Think of us as a lost
The Great Game
How a little girl learns to ride a bike
Grand Rapidians - Part One
CIA World Factbook - Hell
Ivarr the Boneless
Evaline Turns the Worm
Fifteen Men on a Dead Man's Chest
Philosophical theories of truth
Human Genome Project
Earwig
Mojave Desert Phone Booth
D-Day
New Writeups
cryforhelp
Major dictionaries of the world(review)
Glowing Fish
The Uncanny X-Men and the New Teen Titans(thing)
WolfKeeper
Launch loop(idea)
TendoKing
Katana(person)
Wuukiee
Highly ornamental cultivars of brambles still have as many thorns as their wild counterparts(idea)
TheDeadGuy
Editor Log: May 2008(log)
everyday j.Lo
pray do not molest them(thing)
ammie
Bands Who Take Their Names from Eighteenth-century English Poetry and Prose(idea)
shaogo
Under My Thumb(review)
ammie
Rock On(person)
The Custodian
The Dresden Files(thing)
Ouzo
PETA becomes you, a proposed future(fiction)
Ereneta
Stone Soup, Part Two(fiction)
jjen
Sorrier than I ever thought I would be(personal)
locke baron
Moskva class antisubmarine cruiser(thing)
Everything 2 is brought to you by the letter C and The Everything Development Company