Consider a text file that looks like this
-----------------------------------------------------------------
ABC this is the first line
XYZ this is the second line or line 2
MNO this is the catch
POD this is a line
NFY this is a line
POR this is a line
LKM this is a line
ABC this is a line
XYZ this is a line
MNO this is a line
EFG this is the catch
NFY this is a line
POR this is a line
LKM this is a line
ABC this is the first line
XYZ this is the second line or line 2
MNO this is the catch
ABC this is a line
XYZ this is a line
MNO this is a line
EFG this is the catch
----------------------------------------------
Now these lines are divided into two sets.
If the pattern of the first 3 letters in the line go as, firstly case 1
ABC
XYZ
MNO

And case 2 is when specifically EFG occurs as the 4th line after ABC XYZ and MNO.

I'm looking to store the counts of the occurence of case 1 and 2 using perl. It should be noted that ABC XYZ and MNO will always occur in the same sequence and the only catch would be the occurence of EFG which must be noted. the logic I'm using is to check for the occurence of EFG by tracing the end of the MNO line for the new line \n occurence. But for some reason this is not working. Can someone help me with the code for this requirement. Thanks!

I would suggest an easier approach than the one you are taking. Read the file one line at a time. Take the first three characters at the beginning of each line and concatenate them all in one variable, so you will end up with a variable having the value 'ABCXYZMNOPODNFYPORLKMABCXYZMNOEFGNFYPORLKMABCXYZMNOABCXYZMNOEFG' .

Now you want to know the number of times the pattern 'ABCXYZMNO' occurs in the string and the number of times 'ABCXYZMNOEFG' occurs. Using regex you can find all matches of a pattern in a string more easily than trying to do it while looping through a file.

Can you post your code at least.???

What have you done so far.?

Need more info ok ;)

The code I've used serves the purpose for now but I'm looking at more conditions to be applied in my requirement, consequeltly the logic I used satisfies only this basic step, anyways here's the code !

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

open(FILE, "<trial.txt") || die ("Could not read the file");
my @file_data=<FILE>;
close(FILE);

my @line = split (/\\n/,@file_data);

my $count1=0;
my $count2=0;
my $count=0;

foreach my $line (@file_data){

if ($line=~ /(^ABC)/)
{
$count1 = $count1+1;
}
elsif ($line =~ /(^EFG)/)
{
$count2 = $count2+1;
}
}
$count=$count1-$count2;
print "Count \n ABC \n XYZ \n MNO = $count \n";
print "Count \n ABC \n XYZ \n MNO \n EFG = $count2 \n";

exit;

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.