in reply to undefined or zero: looking for an elegant solution
None of the solutions do what you asked--although they may do what you want. That's because a key can exist, yet its corresponding value is undef:
use strict; use warnings; use 5.010; my %hash = ( 'one' => undef, ); say "The key 'one' exists" if exists $hash{one}; say "The key 'two' exists" if exists $hash{two}; --output:-- The key 'one' exists
Note that nothing prints out for the non-existent key: 'two'. Then if you do this:
you will assign 1 to a key that exists--which does not meet your stated requirement.$hash{one} ||= 1; say $hash{one}; --output:-- 1
|
|---|