开发者

Why can't I open files returned by Perl's readdir?

Well, I know this is another newbie question but I'm very frustrated and I'm looking to be enlightened again. With the guidance of you guys, I've already learnt how to use the glob function to read the contents of each file in a directory. Now I'm trying the readdir-foreach combination to do the same thing but I keep receiving "Cannot open file: Permission denied" error. Why is this happening with the same directory , the same files and the same me as Administrator. Can someone kindly show me what I'm doing wrong? Thanks.

The following code uses the glob function and it works:

#! perl
my $dir = 'f:/corpus/';
my @files = glob "$dir/*";
foreach my $file (@files) {
open   my $data, '<',"$file" or die "Cannot open FILE";
while(<$data>) {
...}

The following code fails and the error message says "Cannot open FILE: Permission denied". But why?

#! perl
my $dir = 'f:/corpus/';
opendir (DIR,'f:/corpus/') or 开发者_JAVA技巧die "Cannot open directory:$!";
my @files=readdir(DIR);
closedir DIR;
foreach my $file (@files) {
open   my $data, '<',"$file" or die "Cannot open FILE:$!";
while(<$data>) {
...}


The readdir() function returns only the file's name, not a full path. So you are trying to open e.g. "foo.txt" instead of "f:\corpus\foo.txt".


You should keep in mind that readdir returns directory names and file names. Most likely you are attempting to open one of the special directory entries . or .. which you generally need to filter out if you're using these functions:

foreach my $f (@files)
{
    # skip special directory entries
    if ($f ne '.' && $f ne '..')
    {
        # ...
        print "$f\n";
    }
}

Also note Andy Ross' suggestion that this will only return the relative path, not the full path.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜