alephreish
alephreish

Reputation: 540

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

Is there an efficient way to see, if a hash key assignment resulted in adding a new item or in modifying an existing one? Something similar in behavior to the add function in this Bloom's filter implementation.

In the construct below two lookups are performed: once explicitly with exists and another time implicitly during the assignment. The first lookup is thus logically redundant.

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

Upvotes: 4

Views: 427

Answers (1)

ikegami
ikegami

Reputation: 385744

By "item", I think you mean "key".

If the value is meaningless, you can use the following:

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

If the value is meaningful, you can use the following:

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

If the value is meaningful but always defined, you can use the following:

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

By the way, the first snippet can easily be extended to filter out duplicates from a list.

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

Upvotes: 3

Related Questions