<?xml version="1.0" encoding="windows-1252"?>
<node id="1015561" title="Re^3: Replacing values in an array" created="2013-01-27 00:17:32" updated="2013-01-27 00:17:32">
<type id="11">
note</type>
<author id="333489">
muba</author>
<data>
<field name="doctext">
&lt;p&gt;You can consider a hash to be much like an array, except instead of numerical indexes to access individual elements, you use strings as keys.&lt;/p&gt;

&lt;c&gt;
# Define an array:
my @basket = qw(apple banana cherry);

# Get an element from the array:
# (remember that indexes are 0-based)
print "The second kind of fruit in the basket is $basket[1]\n";

# Change an element:
$basket[1] = "date";
print "Now it is $basket[1]\n";
&lt;/c&gt;

&lt;p&gt;The above example shouldn't be unfamiliar. Now, instead of keeping a &lt;c&gt;@basket&lt;/c&gt; that tells us what kinds of fruit we have in the basket, let's keep a &lt;c&gt;%basket&lt;/c&gt; that can also tell us how much of that kind of fruit we have.&lt;/p&gt;

&lt;c&gt;
# Define the hash:
my %basket = (
    apple    =&gt; 12,
    banana   =&gt;  6,
    cherry  =&gt;  32,   # This final comma is optional,
);                    # but makes it easier to add more lines in the future.

# Get an element from the basket:
print "There are $basket{cherry} cherries in the basket.\n";

# Modify elements:
$basket{cherry}--;
print "Now there are $basket{cherry}.\n";

$basket{banana} *= 2;
print "Double Banana Bonus! $basket{banana} bananas in the basket!\n";

$basket{apple} = 10;

# Add an element:
$basket{date} = 16;


# Get all keys in the hash:
print "Fruits in my basket: ", join(", ", sort keys %basket), "\n";

# Using a variable as a key:
for my $fruit (sort keys %basket) {
    print "You want a(n) $fruit? I have $basket{$fruit} in my basket.\n";
}

# The 'each' function:
while (my ($fruit, $amount) = each %basket) {
    print "There are $amount ${fruit}s in my basket.\n";
}

# Getting rid of an element:
delete $basket{apple};
print "Fruits in my basket: ", join(", ", sort keys %basket), "\n";
&lt;/c&gt;

&lt;p&gt;That pretty much covers the basics of hashes. Nothing to be afraid of, and quite a useful data type!&lt;/p&gt;</field>
<field name="root_node">
1015541</field>
<field name="parent_node">
1015547</field>
</data>
</node>
