Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks. Is there an efficient way to check if a value exists in a hash, and if not, assign 0 (zero) to the key that a user is requesting? Thanks.

Replies are listed 'Best First'.
Re: Perl Hash Behavior.
by GrandFather (Saint) on Oct 18, 2013 at 22:20 UTC

    Perhaps you mean succinct rather than efficient?

    use 5.010; ... $hash{$key} //= 0;

    is succinct, clear (if you know the syntax) and likely about as efficient in terms of fewest processor cycles as you can get. It requires Perl 5.10, but that shouldn't be a problem most places now.

    True laziness is hard work
Re: Perl Hash Behavior.
by LanX (Saint) on Oct 18, 2013 at 20:11 UTC
    > efficient way to check if a value exists in a hash, and if not, assign 0

    golfing

    DB<105> %h=(); print $h{key} //= 0; 0 DB<106> \%h => { key => 0 }

    Update: beware that like this values like undef are not allowed!

    Otherwise better use exists

    Cheers Rolf

    ( addicted to the Perl Programming Language)

Re: Perl Hash Behavior.
by marinersk (Priest) on Oct 18, 2013 at 20:28 UTC
    if (!defined $hash{$key}) { $hash{$key} = 0; }

    Or that new-fangled thing with the //.

Re: Perl Hash Behavior.
by Anonymous Monk on Oct 18, 2013 at 20:09 UTC
    Sorry. I meant if a key exists in a hash.

      I meant if a key exists in a hash.

      Watch out to the vocabulary that you are using. These two things can be done to do something similar to what you want, but they don't do exactly the same thing:

      $hash{'foo'} = 0 unless exists $hash{'foo'}; # Not the same as: $hash{'foo'} = 0 unless defined $hash{'foo'};

      If the hash key exists and the hash has a value for that key, nothing will happen in both cases. If the hash key does not exist, then the hash entry will be created in both cases. So no difference for these two cases.

      There will be a difference if the hash key exists and no value is defined for that key entry. In this case, the first code line above will not modify the hash (since the hash key entry exists), while the second line will assign 0 to the value (since the value is not defined). Think carefully of what you really need. From your description of your need, you probably want the second line, but the correction you made quoted just above throws a bit of doubt into the picture. I still think you probably want the second form.