Forum Moderators: coopster & phranque

Message Too Old, No Replies

Comparing and deleting directory files

         

NevadaSam

11:15 pm on Jul 16, 2006 (gmt 0)

10+ Year Member



I am trying to learn how to compare files I have in a directory to the file names stored in a field of a DBM database. What I want to do is delete the file from the directory if it is no longer in an active database record. This is what I have so far. I believe the script is making the comparison, but no files are being deleted. I made sure there were files in the directory that are not stored in the database file.

#!/usr/bin/perl
# compareData.cgi
print "Content-type: text/html\n\n";
use CGI qw(:standard);
use SDBM_File;
use Fcntl;
use strict;

my ($key, $status, $cat, $remarks, $image, %records, $record);
my (@dir_contents, $dir_contents, $file, $dir_to_open);

$dir_to_open="../../photos";

# open file with handle DIR

opendir(DIR,$dir_to_open) ¦¦ die("Cannot open directory!\n");

# Get contents of directory

@dir_contents= readdir(DIR);

# Close the directory

closedir(DIR);

# Now loop through array and print file names

foreach $file (@dir_contents)
{
if(!(($file eq ".") ¦¦ ($file eq "..")))
{
print "$file <br>\n";
}
}

# #
# #So far, so good. The above code reads the contents of
# #the directory and prints out each file name. I don't
# #need to print the filename but doing so at this points
# #shows this code is good.
# #
# #
# #Now the code below will read the DBM file into memory.
# #I need to compare the filename from the @dir_contents array
# #with what is in the $image field and delete the files that
# #do not exist in the database.
# #

tie(%records, "SDBM_File", "corkboard", O_RDONLY, 0)
or die "Error opening corkboard. $!, stopped";

foreach $key (keys(%records)) {
($status, $cat, $remarks, $image) = split(/\¦/, $records{$key});

#delete the file unless it exists in database
foreach $image(%records) {
unlink $dir_contents unless $image;
}
}
untie(%records );

I really appriciate any help someone can give.

perl_diver

6:01 pm on Jul 17, 2006 (gmt 0)

10+ Year Member



unlink $dir_contents unless $image;

$dir_contents has never been defined in your script.