cseligman has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks: I get an error that says "readdir() attempted on invalid dirhandle DH" from the code below, so what do I do, Thanks, Chet:
#!/usr/bin/perl use strict; use warnings; my $outputfile ="Test_PDB_ID_list.txt"; my $four_char_PDB_ID=''; open (PDB_IDs,">", "$outputfile"); my $PDB_ID= ''; my $dir_to_process= ''; print "What is the directory to process?"; $dir_to_process = <STDIN>; #$dir_to_process = "Targets-IonChannel";-if I used this #line it would + work #open the folder unless (opendir(DH, $dir_to_process)){ print "Cannot open folder $dir_to_process!\n"; } print "$dir_to_process\n"; foreach $PDB_ID (readdir DH){ $four_char_PDB_ID =substr($PDB_ID,0,4); print PDB_IDs "$four_char_PDB_ID\n"; print "$four_char_PDB_ID \n"; }; exit;

What is the directory to process?

Targets-IonChannel

Cannot open folder

Targets-IonChannel

!

Targets-IonChannel

readdir() attempted on invalid dirhandle DH at C:\Users\cseligman\Documents\Eclipseworkspace\DrugTargets\GetPDBnames-1.pl line 21, <STDIN> line 1.

Replies are listed 'Best First'.
Re: Get a DH from <STDIN>?
by ikegami (Patriarch) on Mar 29, 2011 at 17:11 UTC

    Of course you cannot read from a handle you never opened ("Cannot open folder"). The reason it failed to open is that you failed to remove the trailing newline from the line you read from STDIN. chomp it.

    By the way, it's a good idea to also include $! in error messages from open and opendir.

Re: Get a DH from <STDIN>?
by wind (Priest) on Mar 29, 2011 at 17:10 UTC
    When opendir fails, you should die and examine the error message.
    opendir(DH, $dir_to_process) or die "Cannot open $dir_to_process: $!";
    Most likely you just need to chomp your input string
    my $dir_to_process = <STDIN>; chomp $dir_to_process;
Re: Get a DH from <STDIN>?
by jethro (Monsignor) on Mar 29, 2011 at 17:12 UTC

    Add a chomp($dir_to_process); and it should work. Also you might change the 'print "Cannot...' to 'die "Cannot....'. If you can't open the dir then there is no reason to continue

Re: Get a DH from <STDIN>?
by Anonymous Monk on Mar 29, 2011 at 17:09 UTC
    so what do I do,

    When your program fails to open a directory handle, wait for it :), do NOT try to read from it, because the opendir call failed :)

Re: Get a DH from <STDIN>?
by jpl (Monk) on Mar 29, 2011 at 17:50 UTC

    The newline is still attached to the directory name. You'll want to

    chomp($dir_to_process);

    before attempting the opendir.