Pages

Wednesday, May 8, 2013

Perl Error: readdir() attempted on invalid dirhandle

Q. I am seeing "readdir() attempted on invalid dirhandle DIR at" error when attempting to open a directory using readdir function in Perl. How can I resolve this?

The error "readdir() attempted on invalid dirhandle DIR at" clearly states that PERL was unable to open directory by using readdir function. There are number of situations which causes this error

1)Check if user who executed perl script have permissions on that directory or not. User should have read permissions to open a directory in Perl. Check permissions by using ls command.

2)Check if directory exists or not? Sometimes users will forgot to check if directory exists or not before opening a directory. To avoid this we can use below code to check before opening a directory.



opendir DIR, $SRCDIR || die ("Can not open dir $SRCDIR");


Keep this line before readdir function so that it will give you a meaningful error message before reading a directory.

3) Are you reading an input from user? Then make sure that your variable which contain directory name should not contain newline character. So use chop or chomp function to remove last character.

chop($DIR=<>)

This will chop of last character.

Hope this helps someone when dealing with open directory in perl.

0 comments:

Post a Comment