Hi,
I am pretty new to coding and Perl. I am not sure what I am doing wrong in this code.
My goal for this script is to read through text files line by line and check if a match is found at a certain place in line. If a match is found, update count and then print it out later.
The first part is where I am storing all files names in an array that I am supposed to be reading.
I have array1 - @types that has these 2 letter strings(which I am supposed to check for in each file in each line, This variable is found in each line at 41st character.) and array2 - @counts where I am trying to store count if that match is found.
Then I am initializing all elements in array2 to 0 since they are all going to be integers. Then I have code to go though each file, each line and check for a match.
use Data::Dumper;
use List::Util qw(sum);
# Grab text files from archive directory with glob function
@files = glob ('/export/home/date_file*);
$arrCount = scalar(@files);
my @types = ("AB", "AC", "AD", "AE", "FG");
my @counts = ($AB, $AC, $AD, $AE, $FG);
for($i = 0; $i < (@counts) ; $i++ ) {
@counts[$i] = 0;
}
for($i = 0; $i < $arrCount; $i++) {
$file = @files[$i];
open(FILE, $file) or die "Can't open `$file': $!";
@lines = <FILE>;
close FILE;
foreach $line (@lines) {
$str = $line;
$var = substr($str, 41, 2);
for( $i=0; $i<(@types); $i++ ) {
if ( $var eq "@types[$i]" ){
@counts[$i]++;
}
}
}
}
my $sum = 0;
for ( @counts) {
$sum += $_;
}
for( $j=0; $j<(@types); $j++ ) {
print "@types[$j]\t: @sums[$j] \n";
$j = $j + 1;
}
print "Total \t: $sum";
This is what my output should look like(with counts next to each)
AB :
AC :
AD :
AE :
FG :
Total :
I am pretty sure there is something wrong with the logic and I can't figure it out. Please help. Thanks in advance!
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.