Home > Blockchain >  Perl: Counting words
Perl: Counting words

Time:11-30

I just started learning Perl last week.

I have to two files in this directory. But later I might want to add 100 txt file in the same directory. The purpose of this coding is to count the frequency of each word.

File1:
e
f
g 
h 
a 

File2:
a 
b 
c 
d 
e 

In order to easily count, I need to read all the text file into the same array.

So here is my script.

my $dir = 'C:\Perl_Example\Data\New';
my %count;
my $line;

foreach my $fp (glob("$dir/*.txt")) 
{
    open my $fh, "<", $fp or die "can't read open '$fp': $OS_ERROR";
    #open file to read which is each file in dir
        
    while (my $line = <$fh>) #line by line to array
    {
        chomp $line;
        
        foreach my $str ($line =~ /\w /g) 
        {
            $count{$str}  ;
            printf "%-31s %s\n", $str, $count{$str};
        }
    }
}

I expected the result would be like

f                               1
g                               1
h                               1
a                               2
b                               1
c                               1
d                               1
e                               2

but instead it turns like this

e                               1
f                               1
g                               1
h                               1
a                               1
a                               2
b                               1
c                               1
d                               1
e                               2

Please advise.

CodePudding user response:

Don't print anything until after you've processed all of the files.

foreach my $fp (glob("$dir/*.txt")) 
{
    open my $fh, "<", $fp or die "can't read open '$fp': $OS_ERROR";
    #open file to read which is each file in dir
        
    while (my $line = <$fh>) #line by line to array
        {
        chomp $line;
        
        
        foreach my $str ($line =~ /\w /g) 
            {
                $count{$str}  ;
            }
            
        }
}

# We have now processed all of the files and have all of
# our data in %count.

for (keys %count) {
    printf "%-31s %s\n", $_, $count{$_};
}
  • Related