in reply to Get total number of characters in a hash (not memory usage)

Thanks for your suggestions everyone. I suppose my SSCCE was a little too simplified. What I'm evaluating now is actually an array of hashes, for which a few modifications to Davido's soluation seems to work best:
use strict; use warnings; use List::Util 'reduce'; sub hash_char_count { my $orders = shift; my $count = 0; foreach my $order (@$orders) { $count += reduce { $a += length $b } 0, %$order; } return $count; } my $orders = [ { 'OrderDate' => '2019-11-01 00:00:00', 'AlternateKey' => 'D', 'Customer' => '1238756', 'SalesOrder' => '10928', 'CustomerName' => 'Dunder Mifflin', 'ShippingInstrs' => 'Standard' }, { 'OrderDate' => '2020-01-15 00:00:00', 'SalesOrder' => '11349', 'Customer' => '1239451', 'AlternateKey' => 'R', 'CustomerName' => 'Vance Refrigeration', 'ShippingInstrs' => 'Standard' }, { 'OrderDate' => '2020-01-22 00:00:00', 'SalesOrder' => '12954', 'Customer' => '1240029', 'AlternateKey' => 'R', 'CustomerName' => 'A1A Car Wash', 'ShippingInstrs' => 'Next Day' } ]; print hash_char_count($orders);
I'd like to be able to get the character count of any data structure: array of hashes, array of hashes with some array elements, etc... but this works for me for now.

Replies are listed 'Best First'.
Re^2: Get total number of characters in a hash (not memory usage)
by tybalt89 (Monsignor) on Jan 29, 2020 at 18:20 UTC

    Handles any nesting of [] and {}

    #!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11111985 use warnings; use List::Util qw( sum0 ); my $orders = [ { 'OrderDate' => '2019-11-01 00:00:00', 'AlternateKey' => 'D', 'Customer' => '1238756', 'SalesOrder' => '10928', 'CustomerName' => 'Dunder Mifflin', 'ShippingInstrs' => 'Standard' }, { 'OrderDate' => '2020-01-15 00:00:00', 'SalesOrder' => '11349', 'Customer' => '1239451', 'AlternateKey' => 'R', 'CustomerName' => 'Vance Refrigeration', 'ShippingInstrs' => 'Standard' }, { 'OrderDate' => '2020-01-22 00:00:00', 'SalesOrder' => '12954', 'Customer' => '1240029', 'AlternateKey' => 'R', 'CustomerName' => 'A1A Car Wash', 'ShippingInstrs' => 'Next Day' } ]; sub charcount { my $tree = shift; ref $tree or return length $tree; sum0 map charcount($_), ref $tree eq 'HASH' ? %$tree : @$tree; } print charcount($orders), "\n";