Thanks for clearing that up. I think I'm on the right track. What I want to do is add the total words for each section. I am trying to stay within th loop and do the following

%cntr = (
word1 => {
    title1 => count1,
    title2 => count1,
word2 => {
    title1 => count2 + count1,
    title2 => count2 + count1,
etc etc

so that when I end on the last word I will have the total words for each section and I can include that in my output as the last line. Basically I am trying to figure out how to add up all the values for title1, title2, and so on. Should I push all the values to an array then add them. Below totals the number of words in all sections (I already added that before by accident).

#print hash of hashes
foreach my $word ( sort keys %cnter ) {
    print FILEOUT2 "$word : ";
    my $cnter2 = 0;
    for my $sect ( keys %{ $cnter{$word} } ) {
	print FILEOUT2 "$sect = $cnter{$word}{$sect}\n";
                $cnter2 += $cnter{$word}{$sect};
	print FILEOUT2 $cnter2;
    print FILEOUT2 "  \n"; 

By moving where I declare $cnter2 I see how to add all the words in all the sections. I'm missing the next step to add all the words for 1 section.


For anyone that was curious. Here is one way I solved what I was trying to do. I added a new hash in the while loop:

$cnter2{$title}{$_}++ for @line;

This way the title was first. I then added another loop at the end:

foreach my $title (sort keys %cnter2) {
    my ($titleword);
    foreach my $word ( keys %{ $cnter2{$title} } ) {
        $titleword += $cnter2{$title}{$word};
    print FILEOUT "\t$titleword : ";

Last line are section totals. Took me a little while.


Good. But I still think it would be better to just count the words while building the initial data set, it would be less work since perl would only need to parse the file once to get all the data, instead of parse the file, then the data again.

Votes + Comments
All posts have helped me understand Perl more.
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.