Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

checking whether a file exists

Status
Not open for further replies.

Myqns

Programmer
Jul 28, 2004
23
GB
Hello,

I want to check whether a certain list of files exist in a directory.

I have the following code
Code:
@lines = <SOURCE>;
foreach $line (@lines) {
    chomp;
    print $line\n;
    chdir ("i:/FIDESSA/diva/divafiles");    
    if (-e 'i:/fidessa/diva/divafiles/$line') {
	print "File $line exists\n";
    } else {
	print "Oh no $line doesn't exist today!\n";
	
    }
}

I know the file exists in the directory. But, the above code always prints file does not exist. Unable to fix this. The same code works fine if I include the filename in the following line instead of the variable.
Code:
if (-e 'i:/fidessa/diva/divafiles/FID001.pdf') {
	print "File $line exists\n";
    }

Thanks
 
I'm assuming $line = FID001.pdf with no leading spaces...

Have you tried the first loop without the chdir command (Or tried if (-e '$line') instead of your current test)?
 
I checked throughly. There are no leading spaces. I also tried the two ways you have suggested earlier. But, the same results.

Thanks for your post!
 
However, the output printed if the files are not found looks like this.


Oh no FID00025.drkw.txt
doesn't exist today!


That is it spills over two lines. So, I guess there are trailing spaces after the filename when it gets it from the array. I have a 'chomp'. May be it is not sufficient.


Any inputs please?
 
Use double quotes when checking for file existence, i.e.,
if (-e "i:/fidessa/diva/divafiles/$line")
Variable values (as in $line) are not interpolated in single-quoted strings.

Also note that you've got fidessa in upper case in your chdir statement and in lower case when checking for file existence. Be consistent. Note that case does matter, on *nix.

I also suggest checking for success on the chdir, e.g.
chdir("i:/FIDESSA/diva/divafiles") || die qq(Your message here.\n);
 
first thing to try:

replace the print $line\n; with print '--$line--\n'; so we can see what we're actually dealing with.

Let me know what you get.
 
You need to say chomp($line); chomp with no argument chomps $_;
 
Thanks everyone for your wonderful posts. the problem was that it had trailing spaces. Now, I removed the spaces, it works like charm.

Thanks again.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top