开发者

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

I would like $dir and everything underneath it to be开发者_StackOverflow中文版 read only. How can I set this using Perl?


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);


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜