In the example you provide, this will work:

-------------START
%h1     = ("one" => 1, "two" => 2, "three" => 3);
%h2     = ("four" => 4, "five" => 5, "six" => 6);

#  Note that the '&' on function calls is optional, unlike $, @, and %
$ref_h3 = mergehash(_____, _____);

sub mergehash {
        my ($rh_first, $rh_second) = @_;

        { %$rh_first, %$rh_second };  # POINT A
}
-------------FINISH

        The line labelled 'POINT A' does all the work:  it constructs a
new, anonymous hash reference, initializes it, and (since it is the last
value in the function) returns it.  Basically, we dereference the two hash
references back into hashes, unroll them into lists of key/value pairs,
and use them to initialize the new hash we are building.

        Note, however, that if %h1 and %h2 share any keys in common will
end up with the value of whichever hash you list LAST in the hashref.
This problem is without solution within the parameters given; no matter
what you do, Perl's builtin hash type cannot have duplicated keys, and no
key may have more than one value.  Now, you can get around it in a LOT of
ways...you can use array references to store your values (meaning that one
key can hold as many values as you want, hidden inside the array ref),
and/or you can use fancy object-oriented magic to make a magical data
structure that pretends to be a hash but can have duplicate keys.

HTH,

Dave

On Sat, 3 Nov 2001, AMORE,JUAN (HP-Roseville,ex1) wrote:

> Hello Perl Gurus,
> I'm trying to write a program that will merge two hashes together onto a
> third hash called %h3. I need to
> return a reference to %h3 to the main program and print each of the values
> of the hash %h3 using the arrow notation.
> Name of the actual function performing the merge mergehash.  Pass %h1 and
> %h2 to mergehash as references.
> The function call in the main program will be something like the following
> where $ref_h3 will be used to print the values in %h3.
>
>               $ref_h3 = &mergehash(_____, _____);
>
> %h1   = ("one" => 1, "two" => 2, "three" => 3);
> %h2   = ("four" => 4, "five" => 5, "six" => 6);
>
>
>
> Many Thanks!!!:)
> JA
>
>
>
>
>


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to