Muzammil
Muzammil

Reputation: 668

Perl Concatenating 2 hashes based on a certain key

Hi I have two hashes %Asset & %Activity

%Asset
Name,Computer Name
David,X
Clark,Y
Sam,Z

%Activity
Name,Activity
David,A
Clark,B
Sam,C
David,D
Clark,E
Sam,F

The second hash has the name repeated multiple times (can be more than 2) .. I want to get a hash with the concise infromation.. something like

Name,Computer Name,Activity
David,X,A&D
Clark,Y,B&E
Sam,Z,C&F

my idea in a pseudo code kind of way is;

foreach (@Activity{qw[Name]}) {
    push @Asset{qw[Name Activity]}, $Activity['Activity']

}

Upvotes: 2

Views: 56

Answers (1)

Schwern
Schwern

Reputation: 165546

What you want is a hash of hashes. Conceptually, you'd combine all information about an asset into a single hash.

my %dave = (
    name          => "Dave",
    computer_name => "X",
    activity      => "A"
);

Then this goes into a larger hash of all assets keyed by their name.

$Assets{$dave{name}} = \%dave;

If you want to find Dave's activity...

print $Assets{Dave}{activity};

You can pull out all information about Dave and pass it around as a hash reference.

 my $dave = $Assets{Dave};
 print $dave->{activity};

This sort of structure inevitably leads to modelling your assets as objects.

You can learn more about hashes of hashes in the Perl Data Structures Cookbook.

Upvotes: 2

Related Questions