Thats what hashes do. map a unique key to a unique values. But you can make that value an array ref and store your multiple values.
It also looks like you want to apply it recursively. May I ask what you are trying to do?
-Lee
"To be civilized is to deny one's nature."
UPDATE
Here's enough rope to hang yourself with.
Merges N hashes arbitrarily deep. Making it merge arrays as well is left as an exercise for the reader.
Dies on circular references. Not heavily tested.
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
BEGIN {
my %SeenMerged = ();
sub mergehashes{ # Dies on circular references
my @hashrefs = @_;
die "Passed a non hashref" if grep { ref $_ ne 'HASH' } @h
+ashrefs;
my %merged = ();
my @seen = grep { ref $_ eq 'HASH' } @SeenMerged{@hashref
+s}; # Break circular links..
if (@seen){
die "contains a circular reference! bailing...";
}
@SeenMerged{@hashrefs} = @hashrefs;
foreach my $h (@hashrefs){
while (my ($k,$v) = each %$h ){
push @{$merged{$k}}, $v;
}
}
while (my ($k,$v) = each %merged){
my @hashes = grep { ref $_ eq 'HASH' } @$v;
$merged{$k} = $v->[0] if (@$v == 1 && !ref $v->[0]);
+
$merged{$k} = mergehashes(@hashes) if @hashes;
}
delete @SeenMerged{@hashrefs};
return \%merged;
}
}
my %hash1 = (
red => 1,
brown => {
green => 1,
blue => {
yellow => 1,
},
black => 1,
},
gray => 1,
);
my %hash2 = (
white => 1,
brown => {
purple => 1,
},
);
my $merged = mergehashes(\%hash1, \%hash2) ;#or die "Couldn't merge!";
print Dumper($merged);
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.