My aesthetic sense is somewhat offended by scanning the list twice using grep.

Mine too - as well as my common sense (no offense broquaint ;-)

Here's a quick benchmark of my first thought (&for_values), my second thought (&grep_subtract) your method and broquaint's double grep.

#!/usr/bin/perl use strict; use warnings; use Benchmark 'cmpthese'; my %hash = ( foo => 1, bar => 1, baz => 1, one => undef, two => undef, three => undef, ); my ($defined, $undef, $count, @def); sub for_values { defined($_) ? $defined++ : $undef++ for values %hash; } sub grep_values { $defined = scalar (grep defined, values %hash); $undef = scalar (grep !defined, values %hash); } sub grep_subtract { $defined = scalar (grep defined, values %hash); $undef = (scalar keys %hash) - $defined; } sub for_array { $def[ defined $_ ? 1 : 0]++ for values %hash; } cmpthese ( -5, { for => \&for_values, grep => \&grep_values, grep_two => \&grep_subtract, for_array => \&for_array, } ) __END__
I'll just post the summary output from cmpthese: (perl 5.6.1) Rate for_array grep for grep_two for_array 82736/s -- -8% -12% -44% grep 90290/s 9% -- -4% -39% for 94074/s 14% 4% -- -37% grep_two 148846/s 80% 65% 58% --

Using grep is deceptively fast - it looks like using the ternary operator in a single loop is slower than looping twice!

By far the fastest of these is using keys to find the total number of hash elements and subtract the number of defined elements.

I wonder how this would perform as the hash grows?

Update: Moved Benchmark results outside of readmore...


In reply to Re: Re:x2 Counting keys with defined or undefined elements in a hash by jsprat
in thread Counting keys with defined or undefined elements in a hash by Bukowski

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.