Search code examples
perlhashinitializationlookup-tableshashref

Declare and populate a hash table in one step in Perl


Currently when I want to build a look-up table I use:

my $has_field = {};
map { $has_field->{$_} = 1 } @fields;

Is there a way I can do inline initialization in a single step? (i.e. populate it at the same time I'm declaring it?)


Solution

  • Just use your map to create a list then drop into a hash reference like:

    my $has_field = { map { $_ => 1 } @fields };