David B
David B

Reputation: 29998

How do I recursively set read-only permission using Perl?

I would like $dir and everything underneath it to be read only. How can I set this using Perl?

Upvotes: 3

Views: 6483

Answers (3)

Ether
Ether

Reputation: 53986

You could do this with a combination of File::Find and chmod (see perldoc -f chmod):

use File::Find;

sub wanted
{
    my $perm = -d $File::Find::name ? 0555 : 0444;
    chmod $perm, $File::Find::name;
}
find(\&wanted, $dir);

Upvotes: 10

Greg Bacon
Greg Bacon

Reputation: 139601

system("chmod", "--recursive", "a-w", $dir) == 0
  or warn "$0: chmod exited " . ($? >> 8);

Upvotes: 2

Cfreak
Cfreak

Reputation: 19319

Untested but it should work. Note your directories themselves have to stay executable

set_perms($dir);

sub set_perms {
     my $dir = shift;
     opendir(my $dh, $dir) or die $!;
     while( (my $entry = readdir($dh) ) != undef ) {
          next if $entry =~ /^\.\.?$/;
          if( -d "$dir/$entry" ) {
              set_perms("$dir/$entry");
              chmod(0555, "$dir/$entry");
          }
          else {

              chmod(0444, "$dir/$entry");
          }
     }
     closedir($dh);
}

Of course you could execute a shell command from Perl as well:

system("find $dir -type f | xargs chmod 444");
system("find $dir -type d | xargs chmod 555");

I use xargs in case you have a lot of entries.

Upvotes: 1

Related Questions