Your data looks like it warrants a hash of hash rather than one-level hash structure; in other words it suggests something like:
my %HoH = (); # 'my' declares at file scope in this case LoadFile(\%HoH); # passing by reference is more portable # if you later make a module Stats(\%HoH); sub LoadFile{ my $href = shift; # get the actual parameter open my $fileHandle, "<filepath" or die $!; while( <$fileHandle> { my ($st,$to,$te) = split( /\:/ ); $href -> { $st }{ $to } = $te; # load file data into the HoH } close $fileHandle; } sub Stats { my $href = shift; for my $st ( sort keys %$href ) { # in state order my $toref = $href -> { $st }; # ref. to town subhash my ( $count, $sum ) = (0,0); for my $to ( keys %$toref ) { # sum through towns # (any order will do) $count++; $sum += ( $toref -> { $to } ); # accumulate state aggregates } print "$st: " . $sum/$count . "\n"; # average for state = sum/count } }

-M

Free your mind


In reply to Re: Average calculation by Moron
in thread Average calculation by kk1173

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.