jgatrell42 has asked for the wisdom of the Perl Monks concerning the following question:

I am processing a tree of files and I want to keep track of what file I have processed. So what I do is when I process a file I write the name of the file into a log. The log is a straight text file with the full names of the files. ie test1.txt The program comes back with file not found.
use List::Util qw(first); open (LOG, ">>$LogFileName")||die("Can not open Log file\n"); my ($FileProcessed) = first{$_ eq $FileName}<LOG>; close(LOG); if ($FileProcessed){ print("$FileName Found in Log file\n"); }else{ print("$FileName NOT Found in Log file\n"); }
Thanks JGatrell42

Replies are listed 'Best First'.
Re: Find a filename in a text file
by jwkrahn (Abbot) on Feb 11, 2008 at 20:44 UTC

    You are opening the file for append (">>") which is write only which means that you can't read from the LOG filehandle.

    It would probably be better to use a tied hash instead.

Re: Find a filename in a text file
by toolic (Bishop) on Feb 11, 2008 at 20:54 UTC
    Assuming your log file already exists (I named it "file.log" in the code below), this will check if your "test1.txt" exists in the log file:
    #!/usr/bin/env perl use warnings; use strict; my $file_found = 0; my $desired_filename = 'test1.txt'; # Read log file and look to see if desired file is present my $logfile = 'file.log'; open my $log_fh, '<', $logfile or die "Can not open $logfile for readi +ng: $!\n"; while (<$log_fh>) { chomp; if ($_ eq $desired_filename) { $file_found = 1; last; } } close $log_fh or die "Can not close $logfile: $!\n"; # Print result if ($file_found) { print "File $desired_filename found in log file.\n"; } else { print "File $desired_filename NOT found in log file.\n"; }
Re: Find a filename in a text file
by Khen1950fx (Canon) on Feb 11, 2008 at 22:09 UTC
      I got this right out of Perl for System Administration: Chapter 9: Log Files:
      open(LOG, "$LogFilename") or die "Unable to open logfile:$!\n";

      The example from that web page uses open(LOG,"logfile") which is a string literal so the quotes are required. Your example uses a scalar variable so the quotes are not required or desirable, see: What's wrong with always quoting "$vars"?

Re: Find a filename in a text file
by sh1tn (Priest) on Feb 11, 2008 at 21:39 UTC
    Maybe you'll find useful the  -f operator. perldoc -f -f


Re: Find a filename in a text file
by dcd (Scribe) on Feb 12, 2008 at 15:25 UTC
    I didn't see a value for $LogFileName in your script. Did it run with warnings enabled?