vinoth.ree has asked for the wisdom of the Perl Monks concerning the following question:

I have hash which has key and value, the values will be changed frequently to undef or some other values, in a particular time I need to take a count of keys which does not have undef values, How can I take it ?

Replies are listed 'Best First'.
Re: hash count
by moritz (Cardinal) on Mar 25, 2009 at 14:39 UTC
    scalar grep defined($_), values %hash

    If you don't want to grep for defined values, delete the values instead of setting them to undef, then you can the output of scalar %hash.

    See perldata on what exactly the scalar value of a hash is.

    Update: fixed syntax error. Sorry for not writing the update notice in the first place.

      I usually use "scalar keys %hash" to find how many pairs are in a %hash.

      scalar grep defined($_) values %hash

      I think that should be:

      scalar grep defined, values %hash;

      or

      scalar grep { defined } values %hash;
            scalar grep defined($_) values %hashI think that should be: ...
        It could be as you have written it, but I think moritz may have been considering the relative inexperience of the OPer by passing the parameter explicitly rather than implicitly.

        Also, the code fragment was
            scalar grep defined($_), values %hash
        (comma present after the defined($_) built-in call) in moritz's original reply (unless moritz has been updating replies without noting the fact – unlikely!).

        Yes, I forgot the comma after the defined, and updated my post. Thanks to ikegami for noting it.
Re: hash count
by Corion (Patriarch) on Mar 25, 2009 at 14:39 UTC

    There is this fascinating concept of programming. It involves writing code to solve a problem. I think this concept is applicable here.