molson has asked for the wisdom of the Perl Monks concerning the following question:
I've been banging my head against a wall trying to get my code to work for a couple of days now and am giving up to ask for help. I have a directory of logs (pipe delimited) that I am searching for a phone number and returning data if found. I'm using an input file for the search. That part works, but I also want to return a message if a phone number in the input file is not found. It seems simple enough but if a number is not found I get the message for each line of data in each file. I only want one message if the number is not found in any of the files. I think it's a problem with where I'm putting the code in the loop, but I can't figure out where the right spot is.
Here is the code without the part to return a message if a number is not found:
use strict; #use warnings; my $record; my $tele; my $esn; my $coid; my $error; my $comptn; sub search_tn; my $directory = "C:\\TEMP\\files"; opendir( DIR, $directory ) || die "Unable to open directory - $!\n"; my @files = grep /^R/, readdir( DIR ); closedir( DIR ); open( OUTFILE, "> $directory\\search_results.txt" ) || die "Unable to open write file! - $!\n"; open (COMPFILE, "c:\\temp\\files\\search tns.txt") || die "Unable to open search file! $!\n"; while (<COMPFILE>) { $comptn = substr $_, 0,10; search_tn($comptn); } sub search_tn { foreach my $file (@files) { open( FH, "$directory\\$file" ) || die "Unable to open $file - $!\n"; while( <FH> ) { my @record = split /\|/, $_; next until $. > 1; if ($record[0] eq "TLR") { } else { $tele = substr $record[2], 3, 10; if ($comptn == $tele) { print OUTFILE "====TN Found====\n"; print OUTFILE "FILE: $file\n"; print OUTFILE "TN: $tele\n"; $esn = substr $record[3], 3,5; print OUTFILE "ESN: $esn\n"; $coid = substr $record[4], 3,5; print OUTFILE "COID: $coid\n"; $error = substr $record[9], 3,3; if ($error == "") { print OUTFILE "Error: no error \n\n"; } else { print OUTFILE "Error: $error \n"; print OUTFILE "================\n\n"; } } } } close (FH); } }
Here is a variation of the code I was using to return a message if the number is not found.
if ($comptn != $tele) { print OUTFILE "TN $comptn not found \n"; }
as a side note I'm pretty sure my code is not very efficient, if you have suggestions on how I can better write any code feel free to give me suggestions. Thanks!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Need Help With Loops
by jwkrahn (Abbot) on Sep 23, 2009 at 17:45 UTC | |
|
Re: Need Help With Loops
by GrandFather (Saint) on Sep 23, 2009 at 21:20 UTC | |
|
Re: Need Help With Loops
by kennethk (Abbot) on Sep 23, 2009 at 17:16 UTC |