Adding hashes

G

Graham Drabble

Hi,

I have 2 arrays

%a = ('apples' => 2,
'pears' => 1);
%b = ('apples' => 3,
'pears' => 6);

Want I want is to be able to get

%c = ('apples' => 5,
'pears' => 7);

This can be achieved by

my %c;
foreach my $key (keys %a){
$c{$key} = $a{$key} + $b{$key};
}

but I was wondering if there was any way to do it without the loop.

Any ideas?
 
P

Paul Lalli

Graham said:
I have 2 arrays

No you don't [1].
%a = ('apples' => 2,
'pears' => 1);
%b = ('apples' => 3,
'pears' => 6);

You have two hashes.
Want I want is to be able to get

%c = ('apples' => 5,
'pears' => 7);

This can be achieved by

my %c;
foreach my $key (keys %a){
$c{$key} = $a{$key} + $b{$key};
}

but I was wondering if there was any way to do it without the loop.

How about a map?

my %c = map { $_ => $a{$_} + $b{$_} } keys %a;

Of course, this really is just a loop in disguise, as a map is
basically the same as a foreach loop with a push inside....

Paul Lalli

[1] Okay, *technically*, hashes are also known as "associative arrays",
but they're never referred to as simply "arrays". That's a different
structure entirely.
 
D

Dr.Ruud

Graham Drabble schreef:
Hi,

I have 2 arrays

%a = ('apples' => 2,
'pears' => 1);
%b = ('apples' => 3,
'pears' => 6);

Want I want is to be able to get

%c = ('apples' => 5,
'pears' => 7);

This can be achieved by

my %c;
foreach my $key (keys %a){
$c{$key} = $a{$key} + $b{$key};
}

but I was wondering if there was any way to do it without the loop.

ITYM: without the block. There will always be some kind of loop, even if
only hidden like with map, or the Perl6 hyper-operators.

perl -wle '
my %a = (apples => 2, pears => 1 ) ;
my %b = (apples => 3, bears => 6 ) ;

my %c ; $c{$_} = $a{$_} + ($b{$_} or 0) for keys %a ;

print "@{[%c]}"
'

Prints: apples 5 pears 1
 
G

Graham Drabble

Graham said:
I have 2 arrays

No you don't [1].

Sorry, I know it is a hash, see subject. Brain not quite in gear when
writing.
You have two hashes.
How about a map?

my %c = map { $_ => $a{$_} + $b{$_} } keys %a;

Of course, this really is just a loop in disguise, as a map is
basically the same as a foreach loop with a push inside....

Thanks for that and also to Dr Ruud.

I possibly should have also said that in the case I'm currently
working on I can guarantee the hashes have identical keys.
 
D

Dr.Ruud

Graham Drabble schreef:
I possibly should have also said that in the case I'm currently
working on I can guarantee the hashes have identical keys.

Your 'apples pears' communicated the opposite. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,163
Latest member
Sasha15427
Top