user238021
user238021

Reputation: 1221

Build a string from 2 hashes

I have 2 hashes like the following

hash1:
 key      value
 part0     company0
 part1     company1
 part2     company2

hash2:
 key      value
 part0     2B
 part1     4B
 part2     6B

What I would like is to build a string using the 2 hashes like this "part0 company0 2B, part1 company1 4B, part2 company2 6B" (without quotes)

How can I achieve this ?

Upvotes: 1

Views: 63

Answers (2)

Dan
Dan

Reputation: 10786

Well, assuming that you're guaranteed that both hashes have the same keys, you can do something like this:

foreach my $key (sort keys %hash1) {
     print "$key $hash1{$key} $hash2{$key}\n";
}

If they might have different keys you will need to find a way to get either a list union or intersection, which there's probably a function for in List::Compare.

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 753695

my $answer = "";
my $pad = "";
foreach my $key (sort keys %hash1)
{
    $answer .= "$pad$key $hash1{$key} $hash2{$key}\n";
    $pad = ", ";
}
print "$answer\n";

This assumes that hash2 contains a single, simple entry for each key found in hash1 (it may contain extra entries, but it may not contain fewer entries).

Upvotes: 1

Related Questions