I've been working with a program that uses Hashes of Hashes
and have run into some odd results. My understanding was
that a hash key could only have one value, either a string
or a reference. So why is it that the following code
prints "Red Apple", shouldn'y the second line overwrite the
value of $hash{'food'} with a reference?
$hash{'food'} = 'Apple';
$hash{'food'}{'color'} = 'Red';
print "$hash{'food'}{'color'} $hash{'food'}\n";
and if that works, and the key is remembering both the string and
the reference, then why does this print " Apple"?
$hash{'food'}{'color'} = 'Red';
$hash{'food'} = 'Apple';
I'm assuming it's because 'Apple' overwrites the reference,
but wait, it gets weirder.
In the following example, the values of one hash seemingly
effect the values of another (completely unrelated) hash.
$hash1{'food'}{'color'} = 'Red';
$hash1{'food'} = 'Apple';
$hash2{'food'}{'color'} = 'Red';
$hash2{'food'} = 'Apple';
print "hash1: $hash1{'food'}{'color'} $hash1{'food'}\n";
print "hash2: $hash2{'food'}{'color'} $hash2{'food'}\n";
These both print " Apple" but if you swap the first two lines
like so:
$hash1{'food'} = 'Apple';
$hash1{'food'}{'color'} = 'Red';
$hash2{'food'}{'color'} = 'Red';
$hash2{'food'} = 'Apple';
print "hash1: $hash1{'food'}{'color'} $hash1{'food'}\n";
print "hash2: $hash2{'food'}{'color'} $hash2{'food'}\n";
Then they both print "Red Apple"! How could %hash1 effect
%hash2?
I tested this on both Win2000 Perl 5.6.0 and FreeBSD
Perl 5.005.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.