开发者

Beginner question - Perl script can't find file

I am new to Perl and have created a simple Perl program. However, it never seems to find a file on the file syste开发者_开发技巧m. 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?


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();

... 


Write the full path to your file. It should work. For example:

folder/files/file.txt

and probably use " instead of '


Here are some possibilities for what might be wrong:

  1. Regarding the full path: You are using windows and just copied the full path into your string. In this case don't forget to escape the backspaces in your path. For example: C:\myFolder\test.txt must be put into the variable like this: my $filename = "C:\\myFolder\\test.txt"
  2. 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.

  3. 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! :)


Use this script:

my $filename=glob('*.txt');
print $filename;
if (-e $filename)
{
    print "exists";
}
else
{
    print "not found";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜