in reply to Re^3: Counting occurence of a list of word in a file
in thread Counting occurence of a list of word in a file

thanks! It's working fine now! I'll post the code I used, so you all can give me suggestion for improving my programming skills (I'm sorry if they're not good, but I've been using Perl for just a few week, for my Thesis, and it's all really new), or maybe it could be useful for someone with the same problem..
open my $testo, "<File_Input/Testo.txt"; open my $conteggio, ">File_Output/Conteggio.txt"; my %arrayris; while (my $text=<$testo>){ for my $key (keys %hash){ my $value = $hash{$key}; my $count = 0 ; while ($text =~ /\b$key\b/ig) { $count++ ; } ; $arrayris{$key}=$count; } } while ( my ($k,$v) = each %arrayris ) { print $conteggio "($k) => $v\n"; } close $testo; close $conteggio;

Thanks again, to everybody!

Replies are listed 'Best First'.
Re^5: Counting occurence of a list of word in a file
by gone2015 (Deacon) on Nov 11, 2008 at 18:56 UTC

    It's an improvement !

    If your File_Input/Testo.txt file contains more than one line, then I suggest

    $arrayris{$key} += $count ;
    will produce a more complete result. (Perl will happily create an hash entry with (effectively) a zero value when required.)

    You could also consider counting directly in your %arrayris:

    while ($text =~ /\b$key\b/ig) { $arrayris{$key}++ ; } ;

    Other things you might consider:

    • why you read the words into a hash (your %hash) when you only really use the keys... it may be preparatory to some future extension, I cannot tell.

    • similarly what is:

      my $value = $hash{$key};
      doing to justify its existence.

    • recommend use strict ; and use warnings ; -- they will help you keep out of trouble !

    • the code is definitely "quick and dirty". If your either your wordlist or your input are very long, you may want to speed things up... But, the first rule of optimisation is: Don't do it (unless you really have to).