ver*_*ose 2 permissions perl filesize
我正在尝试编写一个简单的perl脚本,它将遍历目录中的常规文件并计算放在一起的所有文件的总大小.但是,我无法获得文件的实际大小,我无法弄清楚原因.这是代码的相关部分.我输入print语句进行调试:
$totalsize = 0;
while ($_ = readdir (DH)) {
print "current file is: $_\t";
$cursize = -s $_;
print "size is: $cursize\n";
$totalsize += $cursize;
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的输出:
current file is: test.pl size is:
current file is: prob12.pl size is:
current file is: prob13.pl size is:
current file is: prob14.pl size is:
current file is: prob15.pl size is:
Run Code Online (Sandbox Code Playgroud)
因此文件大小保持空白.我尝试使用,$cursize = $_但唯一的影响是检索当前和父目录的文件大小,每个4096字节; 它仍然没有获得常规文件的任何实际文件大小.
我已经在网上查看了我在perl上的几本书,似乎perl无法获取文件大小,因为脚本无法读取文件.我通过输入if语句测试了这个:
print "Cannot read file $_\n" if (! -r _);
Run Code Online (Sandbox Code Playgroud)
果然每个文件都有错误,说明文件无法读取.我不明白为什么会这样.有问题文件的目录是我的主目录的子目录,我从我的主目录中的另一个子目录中运行脚本.我已阅读所有相关文件的权限.我尝试将文件模式更改为755(从之前的711),但我仍然得到Cannot read file每个文件的输出.
我不明白发生了什么.我可能会混淆运行perl脚本时权限如何工作,或者我对正确的使用方式感到困惑-s _.我感谢你的指导.谢谢!
Mor*_*kus 11
如果它不仅仅是你的错字-s _而不是正确的-s $_那么请记住,readdir返回相对于你打开的目录的文件名opendir.正确的方法是这样的
my $base_dir = '/path/to/somewhere';
opendir DH, $base_dir or die;
while ($_ = readdir DH) {
print "size of $_: " . (-s "$base_dir/$_") . "\n";
}
closedir DH;
Run Code Online (Sandbox Code Playgroud)
您还可以查看核心模块IO :: Dir,它提供了tie一种以更简单的方式访问文件名和属性的方法.