问题
I am trying to write to an existing file and at the same time change its permissions. For example:
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;
}
This gives output:
Writing file with permissions 0755
Actual file permissions are 0755
Writing file with permissions 0775
Actual file permissions are 0755
Why is the permission still 0755
after the second write? (I would expect it to be 0775
)
回答1:
From 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).
Note the word "newly-created".
This behaviour is not dictated by the module, but by the core sysopen. From the source of 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 ) ) {
We see that sysopen
is used. In the documentation for sysopen it says:
If the file named by FILENAME does not exist and the open call creates it (typically because MODE includes the O_CREAT flag), then the value of PERMS specifies the permissions of the newly created file.
来源:https://stackoverflow.com/questions/26448503/writing-to-existing-file-and-changing-permissions