Search code examples
perlreaddir

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 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>) {
...}

Solution

  • 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".