haru
haru

Reputation: 325

Mapping array additionally to existing hash in Perl

How can I add elements in existing hash like push in array but using mapping?

If I do:

%existing_hash = map { $_ => 1 } @new_elements;

This resets the %existing_hash.

Upvotes: 0

Views: 110

Answers (2)

Dave Cross
Dave Cross

Reputation: 69314

I think I'd do it the simple way:

$existing_hash{$_} = 1 for @new_elements;

But you could also use a hash slice:

@existing_hash{@new_elements} = (1) x @new_elements;

Upvotes: 2

Vivek Pabani
Vivek Pabani

Reputation: 452

Try:

%existing_hash = (%existing_hash, map { $_ => 1 } @new_elements);

Upvotes: 3

Related Questions