vp8
vp8

Reputation: 155

How to update hash by adding keys from the list in perl

Adding a set of keys when declaring a hash is straightforward as -

my %hash = map { $_ => 1 } @list;

If I want to add more keys from another list, how can I achieve that with single line?

Upvotes: 1

Views: 104

Answers (1)

zdim
zdim

Reputation: 66899

With %hash declared you may use @hash{LIST}, with existing or new keys in LIST

@hash{ @more_keys } = @values_for_new_keys;

See Slices in perldata


If you meant to initiliaze the new keys to a fixed value, you can do for example

@hash { @more_keys } = (1) x @more_keys;

where (1) x N returns a list of 1s of length N, and @more_keys in scalar context returns its length.

Upvotes: 3

Related Questions