Can't open the directory, or is something wrong with my (Perl) code?

I have a logspath.txt file logspath.txt that is contained in the path to the log directory on the machine. one directory of each line. Although the directory exists, Perl says it does not.

 #!/usr/bin/perl -w open FILE,"logspath.txt" or die $!; while (<FILE>){ print $_; opendir ($DIR,chomp($_)) or die $!; 

When I run the script, I get:

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

Directory List:

 ~$ 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 tips?

+4
source share
3 answers

chomp does not have a significant return value, which can then be passed to opendir . You need to chomp your line in a separate statement, above opendir .

  chomp; opendir DIR, $_ or die ... 
+10
source

It should be a comment, but posting the code in the comments really doesn't work, so I do this CW.

Here's how to write this β€œbetter” for some meaning 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 files and directory directories, use the three arguments of the open form and specify the name of the file or directory that you tried to open in the error message enclosed in quotation marks or brackets to see what was actually passed open or opendir .

+4
source

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 if the directory is available or not. If we check the catalog, it is very useful.

-1
source

Source: https://habr.com/ru/post/1303005/


All Articles