in reply to Need help with unlink error

Not you question I know, but:
close $directory;
will fail as well. $directory is the name of the directory, not the directory handle. You probably want:
closedir(DIR);
and you could move that earlier in the code, after your readdir.