2014-10-19 51 views
1

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

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

回答

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标志),然后烫发值指定新创建的权限文件。

+0

谢谢,但这对我来说似乎是一种奇怪的方法。这意味着如果你想使用'perms'选项来'write_file',你首先必须检查文件是否已经存在。如果是这样的话,你必须明确地删除它,或者在你编写文件后使用'chmod' .. – 2014-10-19 08:46:55

+1

这不是由模块控制,而是由'sysopen'控制。我将添加文档以向您展示。 – TLP 2014-10-19 09:05:08