in reply to Count of HoA elements
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
| A reply falls below the community's threshold of quality. You may see it by logging in. |