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!


In reply to Read through directory and return matched data by JonDepp

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.