Can't open directory, or what's wrong with my (Perl) code?
문제
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?
해결책
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 ...
다른 팁
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.
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.