写入现有文件并更改权限

时间:2014-10-19 07:50:23

标签: perl

我正在尝试写入现有文件,同时更改其权限。例如:

use warnings;
use strict;
use File::Slurp 'write_file';

my $script="#! /bin/bash
echo \"Hello\"
";

my $saveName='test.sh';
unlink $saveName if -f $saveName;
writeFile($saveName,$script,0755);
writeFile($saveName,$script,0775);


sub writeFile {
   my ($saveName,$script,$mode) = @_;

   printf "Writing file with permissions %04o\n", $mode & 07777;
   write_file($saveName,{perms=>$mode},\$script);
   my $actualMode = (stat($saveName))[2];
   printf "Actual file permissions are %04o\n", $actualMode & 07777;
}

这给出了输出:

Writing file with permissions 0755
Actual file permissions are 0755
Writing file with permissions 0775
Actual file permissions are 0755

为什么第二次写入后权限仍然是0755? (我希望它是0775

1 个答案:

答案 0 :(得分:2)

来自the documentation

perms

The perms option sets the permissions of newly-created files. This value is 
modified by your process's umask and defaults to 0666 (same as sysopen).

请注意“新创建”一词。

此行为不是由模块决定的,而是由核心sysopen决定的。来自File::Slurp的来源:

                my $perms = $opts->{perms} ;
                $perms = 0666 unless defined $perms ;

#printf "WR: BINARY %x MODE %x\n", O_BINARY, $mode ;

# open the file and handle any error.

                $write_fh = local( *FH ) ;
#               $write_fh = gensym ;
                unless ( sysopen( $write_fh, $file_name, $mode, $perms ) ) {

我们看到使用了sysopen。在the documentation for sysopen中它说:

  

如果FILENAME 指定的文件不存在且打开调用创建它(通常因为MODE包含O_CREAT标志),则PERMS的值指定新创建的文件的权限。 / p>