Search code examples
perlperl-module

Perl : search a keywords from a file and display the occurence


I have two files 1. input.txt 2. keyword.txt

input.txt has contents like

.src_ref 0 "call.s" 24 first
      0x000000    0x5a80 0x0060         BRA.l 0x60
.src_ref 0 "call.s" 30 first
      0x000002    0x1bc5                RETI
.src_ref 0 "call.s" 31 first
      0x000003    0x6840                MOV R0L,R0L
.src_ref 0 "call.s" 35 first
      0x000004    0x1bc5                RETI

keyword.txt has contents

MOV
BRA.l
RETI
ADD
SUB
..
etc

Now I want to read this keyword.txt file and search it in input.txt file and find how many times MOV has occured,how many times BRA.l has occured and so on.

So far I have managed to get it working from a single file itself. here is the code

#!/usr/bin/perl
use strict;
use warnings;

sub retriver();

my @lines;
my $lines_ref;
my $count;
$lines_ref=retriver();
@lines=@$lines_ref;
$count=@lines;
print "Count :$count\nLines\n";
print join "\n",@lines;

sub retriver()
{
    my $file='C:\Users\vk18434\Desktop\input.txt';
    my $keyword_file = 'C:\Users\vk18434\Desktop\keywords.txt';
    open FILE, $file or die "FILE $file NOT FOUND - $!\n";
    my @contents=<FILE>;

    open FILE, $keyword_file or die "FILE $file NOT FOUND - $!\n";
    my @key=<FILE>;


    my @filtered=grep(/^$key$/,@contents);
   #my @filtered = grep $_ eq $keywords,@contents;
    return \@filtered;   
}

Output should look like:

MOV appeared 1 time
RETI appeared 2 times 

Any help is appreciated. Request you to please help on this !!


Solution

  • Check this and try:

    #!/usr/bin/perl
    use strict;
    use warnings;
    
    my (@text, @lines);
    my $lines_ref;
    my $count;
    $lines_ref = &retriver;
    
    sub retriver
    {
        my $file='input.txt'; 
        my $keyword_file = 'keywords.txt';
        open KEY, $keyword_file or die "FILE $file NOT FOUND - $!\n";
        my @key=<KEY>;
        my @filtered;
        foreach my $keys(@key)
        {
            my $total = '0';
            chomp($keys);
            open FILE, $file or die "FILE $file NOT FOUND - $!\n";
            while(<FILE>)
            {
                my $line = $_;
                my $counter = () = $line =~ /$keys/gi;
                $total = $total + $counter;
            }
            close(FILE);
            print "$keys found in $total\n";
        }
    }