Declare and populate a hash table in one step in Perl

Currently, when I want to create a lookup table, I use:

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

Is there a way to do inline initialization in one step? (i.e. fill it at the same time, am I announcing this?)

+5
source share
3 answers

Just use your map to create a list, then go to the hash link, for example:

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

Update: Sorry, this does not do what you want for sure, since you still need to declare $ has_field first.

You can use the hash fragment:

@{$has_field}{@fields} = (1)x@fields;

The right side uses the operator xto repeat one by the scalar value of @fields (i.e. the number of elements in your array). Another option in the same vein:

@{$has_field}{@fields} = map {1} @fields;
+3

2-5 , lookup . , , :

if ( $cand_field ~~ \@fields ) { 
   do_with_field( $cand_field );
}

It’s good to remember that with 5.10, Perl now has a native way of asking “is this an unchecked value of any of these known values”, this is a smart coincidence.

+2
source

All Articles