Sounds like the typical impossible "I want to do iterative task X without iterating" request. Use List::Util and map and you can hide most of it, though.

use List::Util qw( sum ); use YAML::Syck qw( Load ); my $hash = Load( do { local $/; <DATA> } ); my $count = sum( map { scalar @{ $hash->{ $_ } } } keys %${hash} ); print $count, "\n"; __END__ foo: - A - B - C bar: - D - E baz: - F - G - H

Addendum: Just to make things clear: as others have below I'm interpreting "a total count of elements in a Hash of Arrays" to mean "a sum of the count of elements in each arrayref contained in a hash". And just to add more "twaddle", a Ruby version:

require 'yaml' hash = YAML::load( <<EOT ) foo: - A - B - C bar: - D - E baz: - F - G - H EOT count = hash.values.inject(0) { |s,a| s += a.size } puts count ## O(1) version, akin to ikegami's below o_1_count = 0 hash.each_value { |a| o_1_count += a.size } ## Duuurh, Hash isa Enumerable so it has an inject itself or_even_count = hash.inject( 0 ) { | s, (k,v) | s += v.size }

Addendum Update: Changed Ruby version to use hash.values rather than hash.keys, as seen below, which is actually a cleaner implementation than mine above. Also added (what should be :) an O(1) Ruby implementation. And also added using Hash#inject directly rather than iterating over values.


In reply to Re: Count of HoA elements by Fletch
in thread Count of HoA elements by sweetblood

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.