Reputation: 11
I am new to Perl and have created a simple Perl program. However, it never seems to find a file on the file system. The code is:
my $filename = 'test.txt';
if (-e $filename)
{
print "exists";
}
else
{
print "not found";
}
I have also tried to use the exact path of the file "test.txt" but it still does not work; it never finds the file. Does anybody know what I'm doing wrong?
Upvotes: 1
Views: 5471
Reputation: 1112
Here are some possibilities for what might be wrong:
C:\myFolder\test.txt
must be put into the variable like this: my $filename = "C:\\myFolder\\test.txt"
Your script uses another directory than the one your file is in. Here's how you can find out where your script is executed and where it looks for the relative file path test.txt
:
use strict;
use Cwd;
print getcwd;
If you are in the wrong filepath you have to switch to the right one before you execute your script. Use the shell command cd
for this.
You are in the right directory and/or are using the right full path but the file has another name. You can use perl to find out what the actual name is. Change into the directory where the file is before you execute this script:
use strict;
opendir my $dirh, '.';
print "'", join ("'\n'", grep $_ ne '.' && $_ ne '..', readdir $dirh), "'\n";
closedir $dirh;
This prints all files in the current directory in single quotes. Copy the filename from your file and use it in the code.
Good luck! :)
Upvotes: 0
Reputation:
Write the full path to your file. It should work. For example:
folder/files/file.txt
and probably use " instead of '
Upvotes: 0
Reputation: 11
Use this script:
my $filename=glob('*.txt');
print $filename;
if (-e $filename)
{
print "exists";
}
else
{
print "not found";
}
Upvotes: -1
Reputation: 46453
Your code seems correct, which either means that "test.txt" really doesn't exist (or if there is, it's not in the working directory).
For example, if you have this:
/home/you/code/test.pl
/home/you/test.txt
And run your code like this:
$ cd code
$ perl test.pl
Then your test file won't be found.
It may help to make your script print the current working directory before it does anything:
use Cwd;
print getcwd();
...
Upvotes: 3