The following simple Perl script will list the contents of a directory, with the directory listed as an argument to the script. How, on a Linux system can I capture permission denied errors? Currently if this script is run on a directory that the user does not have read permissions to, nothing happens in the terminal.
#!/bin/env perl
use strict;
use warnings;
sub print_dir {
foreach ( glob "@_/*" )
{print "$_\n"};
}
print_dir @ARGV
The glob
function does not have much error control, except that $!
is set if the last glob fails:
glob "A/*"; # No read permission for A => "Permission denied"
print "Error globbing A: $!\n" if ($!);
If the glob succeeds to find something later, $!
will not be set, though. For example glob "*/*"
would not report an error even if it couldn't list the contents for a directory.
The bsd_glob
function from the standard File::Glob
module allows setting a flag to enable reliable error reporting:
use File::Glob qw(bsd_glob);
bsd_glob("*/*", File::Glob::GLOB_ERR);
print "Error globbing: $!\n" if (File::Glob::GLOB_ERROR);
Use File::Find, which is a core module and is able to control everything on a file.
#!perl
use 5.10.0;
use strict;
use warnings;
use File::Find;
find {
wanted => sub {
return if not -r $_; # skip if not readable
say $_;
},
no_chdir => 1,
}, @ARGV;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.