theiss has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
I'm wondering if there's an easier way to get the sizes of hash elements which are also hashes.

IE:
INPUT FORMAT Volume-Chapter-Section-Item (value):
B-001-01-01 (2)
...
B-999-99-99 (x)

while (<>) { if (/^(\w{1})\-(\d{3})\-(\d{1,2})\-(\d{1,2})\s+\((\d+)\)/) { # print "$1, $2, $3, $4, $5\n"; $hash{$1}{$2}{$3}{$4} = $5; } }

I'm trying to find how many Items in a Section,
How many Sections in a Chapter,
How many Chapters in a Volume.
Is there an easier way?

I know that I can get the number of volume by using "scalar keys %hash", but how do I drill down?

TIA

Theiss

Replies are listed 'Best First'.
Re: How to find size of each hash of hashes
by GrandFather (Saint) on Sep 24, 2011 at 02:41 UTC

    Record the information as you parse the input:

    use strict; use warnings; use Data::Dump; my %volumes; while (<DATA>) { next if ! /^(\w{1})\-(\d{3})\-(\d{1,2})\-(\d{1,2})\s+\((\d+)\)/; ++$volumes{$1}{-chapters} if ! exists $volumes{$1}{$2}; ++$volumes{$1}{-sections} if ! exists $volumes{$1}{$2}{$3}; ++$volumes{$1}{-items} if ! exists $volumes{$1}{$2}{$3}{$4}; $volumes{$1}{$2}{$3}{$4} = $5; } print Data::Dump::dump (\%volumes); __DATA__ B-001-01-01 (2) B-001-01-02 (1) B-001-02-01 (3) B-001-02-02 (4) B-001-02-03 (5) B-002-01-01 (0)

    Prints:

    { B => { "-chapters" => 2, "-items" => 6, "-sections" => 3, "001" => { "01" => { "01" => 2, "02" => 1 }, "02" => { "01" => 3, "02" => 4, "03" => 5 }, }, "002" => { "01" => { "01" => 0 } }, }, }
    True laziness is hard work
Re: How to find size of each hash of hashes
by Anonymous Monk on Sep 24, 2011 at 01:40 UTC