如果文件权限大于755,如何检入Perl?

Hoz*_*ozy 5 perl file-permissions

对于unix文件,我想知道Group或World是否对该文件具有写入权限.

我一直在考虑这些问题:

my $fpath   = "orion.properties";
my $info    = stat($fpath) ;
my $retMode = $info->mode;
$retMode = $retMode & 0777;

if(($retMode & 006)) {
  # Code comes here if World has r/w/x on the file
} 
Run Code Online (Sandbox Code Playgroud)

谢谢.

Jon*_*ler 13

你接近你的提议 - 使用stat有点偏离(但在第二个想法,你必须使用File::stat;如果你的代码完成它会有所帮助),掩码常量是错误的,并且评论有点不合需要:

use strict;
use warnings;
use File::stat;

my $fpath   = "orion.properties";
my $info    = stat($fpath);
my $retMode = $info->mode;
$retMode = $retMode & 0777;

if ($retMode & 002) {
    # Code comes here if World has write permission on the file
}     
if ($retMode & 020) {
    # Code comes here if Group has write permission on the file
}
if ($retMode & 022) {
    # Code comes here if Group or World (or both) has write permission on the file
}
if ($retMode & 007) {
    # Code comes here if World has read, write *or* execute permission on the file
} 
if ($retMode & 006) {
    # Code comes here if World has read or write permission on the file
} 
if (($retMode & 007) == 007) {
    # Code comes here if World has read, write *and* execute permission on the file
} 
if (($retMode & 006) == 006) {
    # Code comes here if World has read *and* write permission on the file
}
if (($retMode & 022) == 022) {
    # Code comes here if Group *and* World both have write permission on the file
}
Run Code Online (Sandbox Code Playgroud)

问题标题中的术语"如果文件权限大于755,如何检入Perl?即Group/World有写权限'有点怀疑.

该文件可能具有权限022(或更合理地,622),并且将包括组和世界写入权限,但这两个值都不能合理地声称为"大于755".

我发现有用的一组概念是:

  • 设置位 - 权限字段中必须为1的位.
  • 复位位 - 权限字段中必须为0的位.
  • 不关心位 - 可以设置或重置的位.

例如,对于数据文件,我可能需要:

  • 设置0644(所有者可以读写;组和其他可以读取).
  • 重置0133(所有者无法执行 - 它是一个数据文件;组和其他不能写或执行).

更有可能的是,对于数据文件,我可能需要:

  • 设置0400(所有者必须能够阅读).
  • 重置0133(没有人可以执行;组和其他人不能写).
  • 不关心0244(无论主人是否可以写;无论是组还是其他人都可以阅读).

目录略有不同:执行权限意味着您可以将目录设为当前目录,或者如果您知道其名称则访问目录中的文件,而读取权限意味着您可以找到目录中的文件,但是您不能没有执行权限也可以访问它们.因此,你可能有:

  • 设置0500(所有者必须能够读取和使用目录中的文件).
  • 重置0022(组和其他人必须无法修改目录 - 删除或添加文件).
  • 不在乎0255(不关心用户是否可以创建文件;不关心组或其他人是否可以列出或使用文件).

注意,置位和复位位必须是不相交的(($set & $rst) == 0)),位的总和将始终为0777; 可以从中计算"不关心"位0777 & ~($set | $rst).

  • 请使用[Fcntl](http://p3rl.org/Fcntl)模式常量(`S_I*`)而不是幻数. (2认同)
  • 对于像我这样古老的模糊,常量比`Fcntl`的字母汤更容易阅读.单独地,常量更具可读性,但是`S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH`比`0755`更难读.但是,你可能认为使用字母汤是"更好的风格".我想我可以定义一个方便的常量:`使用常量S_I755 =>(S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);`?(是的,这应该是个笑话.)也许`使用常量S_RWXR_XR_X =>(S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);`更可口. (2认同)