in reply to Re^2: to loop through an array
in thread to loop through an array and store each of the subtotals in the elements of another array

it appears that my hit array is taking the element names not the number of occurrences. I have re-arranged the code
for my $element (@findle) { if (/\Q$element\E/ ) { print "$_\n"; $number++; # push @hit $element; push(@hit, $number); #@lines = # print ("there are : " . $number); } }
what i am trying todo is store the number of occurences for each of the words in the findle array

Replies are listed 'Best First'.
Re^4: to loop through an array
by kennethk (Abbot) on May 12, 2011 at 21:48 UTC
    Ahh, I misunderstood your spec. Rather than just accumulating with push, you would be better served with a hash. In this case, you could accumulate frequencies with something like:

    my %count; for my $element (@findle) { if (/\Q$element\E/ ) { print "$_\n"; $number++; # push @hit $element; $count{$element}++; #@lines = # print ("there are : " . $number); } } for my $element (@findle) { print "$element\t=>$count{$element}\n"; }

    Hashes are probably Perl's greatest strength. A read through of perldata will tell you a bit more about them.

      I am not sure I fully understand the data that is being printed. print "$element\t=>$count{$element}\n"; I seem to getting a strange error Use of uninitialized value in concatenation (.) or string at searchfile.pl line 91, <FILE> line 1023078. Is there a problem with the hash and how its counting the elements
        There are two possibilities I see here. First, you may not be assigning anything to $_. If you are not getting any numerical output, this is your issue.

        Second, if not every key gets hit, then some elements will never be initialized. You can fix this either by initializing all elements in %count to zero before the loop ($count{$_} = 0 for @findle;) or limit your output to cycling over keys where you got hits:

        for my $element (sort keys %count) { print "$element\t=>$count{$element}\n"; }