JonDepp has asked for the wisdom of the Perl Monks concerning the following question:
Hello,
I have a directory of text files and I am trying to write a script that opens the directory and then opens each subsequent file and reads each file line by line looking for a variable (acct_number) and if it finds that variable to output only the data pertaining to that variable. The text data looks like this:
NAME DOE, JOHN HIC XXXXXXXXXX ACNT XXXXXXXX + ICN XXXXXXXXXXXXX ASG Y MOA MA01 MA18 1234567891201 120109 22 001 72070 26 38.00 11.45 + 0.00 2.29 CO-45 26.55 9.16 + PR-2 2.29 PT RESP 2.29 CLAIM TOTALS 38.00 11.45 + 0.00 2.29 26.55 9.16 ADJ TO TOTALS: PREV PD INTEREST 0.00 LATE +FILING CHARGE 0.00 NET 9.16
I want to grab all the data between NAME and ADJ TO TOTALS if the acct_number variable matches the ACNT number of the data. There are many text files in the directory and they all are setup like this. The code I have below opens the directory and each file, but does not return any output even though I know the acct_number matches one within the data.
use strict; use warnings; my $dir = "V:/"; open OUTPUT, "> PEP/dirtest.txt" or die$!; print "What is acct number ?"; my $acct_number = <STDIN>; my @files; my @data; my @lines; my $file; my $flag1; my $flag2; opendir(BIN, $dir) or die "Can't open $dir: $!"; @files = map {$dir.'/'.$_} grep { $_ !~ /^\./ } readdir BI +N; { foreach $file (@files) { open FH, "$file"; while (<FH>) { $flag2 = 1 if $flag1 and /$acct_numbe +r/; $flag1 = 1 if /NAME/; push @lines, $_ if $flag1; if (/ADJ TO TOTALS:/) { print OUTPUT @lines if $flag2; $flag1=0; $flag2=0; @lines=(); } } } } closedir(BIN);
If anyone could tell me why I am not getting any output I would be most grateful!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Read through directory and return matched data
by zentara (Cardinal) on Nov 09, 2010 at 16:37 UTC | |
by JonDepp (Novice) on Nov 09, 2010 at 16:58 UTC | |
|
Re: Read through directory and return matched data
by locked_user sundialsvc4 (Abbot) on Nov 09, 2010 at 18:58 UTC | |
|
Re: Read through directory and return matched data
by umasuresh (Hermit) on Nov 09, 2010 at 16:42 UTC | |
|
Re: Read through directory and return matched data
by Cristoforo (Curate) on Nov 10, 2010 at 01:22 UTC |