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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With