tags:

views:

209

answers:

3

Hi all,

I have a file name logspath.txt which contain on the logs directory path on the machine. one directory each line. Although the directory exist, Perl say it doesn't.

#!/usr/bin/perl -w

open FILE,"logspath.txt" or die $!;
while (<FILE>){
   print $_;
   opendir ($DIR,chomp($_)) or die $!;

When I'm running the script I get:

/home/amosa/
No such file or directory at archive.pl line 6, <FILE> line 1.

Listing the directory :

~$ ls -l /home/amosa/
total 6
drwxr-xr-x  11 amosa    prodapp     1024 Mar  2 12:49 deploy
drwxr-xr-x   2 amosa    prodapp      512 Mar  2 12:39 lib
-rw-r--r--   1 amosa    prodapp      787 Mar  2 11:02 s

Any advice?

+7  A: 

chomp has no meaningful return value that you can then pass onto opendir. You need to chomp your string in a separate statement, above the opendir.

 chomp;
 opendir DIR, $_ or die ...
Chris Jester-Young
+1: good catch.
codaddict
+2  A: 

This should be a comment but posting code in comments does not really work so I am making it CW.

Here is how to write this "better" for some value of better:

#!/usr/bin/perl

use strict; use warnings;

my $logs_file = 'logspath.txt';

open my $FILE, '<', $logs_file
    or die "Cannot open '$logs_file': $!";

while ( my $dir = <$FILE> ) {
    print $dir and chomp $dir;
    opendir my $dir_h, $dir
        or die "Cannot open directory '$dir': $!";
    # do something with $dir_h
}

In short, use lexical file and directory handles, use the three argument form of open and include the name of the file or directory you were trying to open in the error message enclosed in quotation marks or brackets to see what was actually passed to the open or opendir call.

Sinan Ünür
Or you can `use autodie;` and get useful error messages without having to write "or die" all over the place.
cjm
A: 

Dear Friend,

    use strict; 
    use warnings;

    open my $FILE, '<logspath.txt'
     or die "Cannot open '$logs_file': $!";

    while ( my $dir = <$FILE> ) {
        print $dir and chomp $dir;
            if( -d $dir)
            {
        opendir my $dir_h, $dir
            or die "Cannot open directory '$dir': $!";
        # do something with $dir_h
    }
     else
{
     print " Can't open directory $!\n";
}
}

Here "-d" is used to check the directory is available or not. If we check the directory it is very useful.

muruga
thanks to all i learned allot
DoronS
I don't think it's very useful to use -d in this way. All you've done is make the code more complex, without any benefit.Just try the opendir, and if it fails, then handle that failure.
gorilla