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

Dear monks, My intention is to count the number of words in List 2, that contain each of the letters in List 1. When i run the code the first count is fine, however, the subsequent counts are added to the previous ones, such that the final count is the sum of all the counts, not the count of how many "words" contain an "F", as i want it to be. Where am i going wrong? Here is my code.

use warnings; use strict; my $count=0; my @list1 = ("A", "B", "C", "D", "E", "F"); my @list2 = ("AXE", "DOG", "CAT", "FOOD", "TRANCE"); for (my $i=0; $i<scalar(@list1); $i++){ for (my $j=0; $j<scalar(@list2); $j++){ my $word = $list2[$j]; my $letter = $list1[$i]; if ($word =~ /$letter/){ $count++; } } print "$count \n"; }

Replies are listed 'Best First'.
Re: Nested loops; Evaluations array elements are done repeatedly (cross-post)
by toolic (Bishop) on Nov 19, 2013 at 00:50 UTC
Re: Nested loops; Evaluations array elements are done repeatedly
by BrowserUk (Patriarch) on Nov 19, 2013 at 00:47 UTC
    When i run the code the first count is fine, however, the subsequent counts are added to the previous ones, such that the final count is the sum of all the counts, not the count of how many "words" contain an "F", as i want it to be. Where am i going wrong?

    Can you really not see that having counted the first word, that unless you reset the count to zero before starting on the second, when you increment the count for the second word, it will continue from where it got to after the first word?


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Nested loops; Evaluations array elements are done repeatedly
by AnomalousMonk (Archbishop) on Nov 19, 2013 at 18:32 UTC

    The second stackoverflow answer you received (from drmrgd — if that is indeed the selfsame monk cavorting without the precincts of Monastery) is a succinct and very Perlish solution. For extra credit on your assignment, expand that approach to capture and display the actual words that contain each letter. The printed output might look something like:

    Number of words found for each letter: A: 3 (AXE CAT TRANCE) B: 0 C: 2 (CAT TRANCE) D: 2 (DOG FOOD) E: 2 (AXE TRANCE) F: 1 (FOOD)
Re: Nested loops; Evaluations array elements are done repeatedly
by Laurent_R (Canon) on Nov 19, 2013 at 07:13 UTC

    You probably need one counter per letter. So probably an array or, better, a hash, of counters.