hashmap - Perl hashes: assign value to a key and see if the key was defined -


is there efficient way see, if hash key assignment resulted in adding new item or in modifying existing one? similar in behavior add function in bloom's filter implementation.

in construct below 2 lookups performed: once explicitly exists , time implicitly during assignment. first lookup logically redundant.

my %hash; $key; ... $existed = exists $hash{$key}; $hash{$key} = 1; 

by "item", think mean "key".

if value meaningless, can use following:

my $dup = $hash{$key}++; 

if value meaningful, can use following:

my $dup = exists($hash{$key}); $hash{$key} = $val; 

if value meaningful defined, can use following:

my $ref = \$hash{$key}; $dup = defined($$ref); $$ref = $val; 

by way, first snippet can extended filter out duplicates list.

my %seen; @unique = grep !$seen{$_}++, @list; 

Comments