drewboy has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I have two hashes, both of which result from a MYSQL query. The first hash, for example, looks like this:
$cat = ('username' => 'Drew', 'password' => 'Boy');
The hash above came from a bigger set of hashes that came from a mysql query that was split. This is assuming that the query had many results.

There is another mysql query that results to a hash (let's call it $results) containing several smaller sets of hashes. A sample 'smaller hash' from this query would look like:

$link = ('Name' => 'Andy', 'PW' => 'Girl');
My question is, how can I insert the first sample hash ($cat) to $results and at the same time change the names of the keys to 'Name' and 'PW' in place of 'username' and 'password'? Any help will be very much appreciated.

Replies are listed 'Best First'.
Re: Joining and Applying a different hash to another
by dragonchild (Archbishop) on May 14, 2004 at 20:35 UTC
    Well, it sounds like you have two hashes, each containing the same type of keys, but they don't have the same key names. So, it sounds like you need a third hash, mapping old_key to new_key.
    my %keymap = ( username => 'Name', password => 'PW', ); my $old = { username => 'Drew', password => 'Boy' }; my $new = {}; foreach my $k (keys %$old) { $new->{$keymap{$k}} = $old->{$k}; }

    ------
    We are the carpenters and bricklayers of the Information Age.

    Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

    I shouldn't have to say this, but any code, unless otherwise stated, is untested

Re: Joining and Applying a different hash to another
by Zaxo (Archbishop) on May 14, 2004 at 20:36 UTC

    Something like, @{$results}{qw/Name PW/} = @{$cat}{qw/username password/}; Those are hash slices on the dereferenced hashes.

    After Compline,
    Zaxo

Re: Joining and Applying a different hash to another
by duff (Parson) on May 14, 2004 at 20:39 UTC
    Unless I'm missing something ...
    my %trans = ('username' => 'Name', 'password' => 'PW'); for my $k (keys %hash1) { $hash2{$trans{$k}} = $hash1{$k} }