简体   繁体   English

如何从Perl中的命令行参数计算文件的大小

[英]How to calculate size of a file from the command line arguments in perl

I was trying out a sample program that can calculate the size of the file given in command line arguments. 我正在尝试一个示例程序,该程序可以计算命令行参数中给定的文件大小。 It gives the size correctly when I have a file name stored inside a variable, but doesn't output a result when got the filename from the command line arguments. 当我将文件名存储在变量中时,它可以正确提供大小,但是从命令行参数获取文件名时,它不会输出结果。

#! /usr/bin/perl 
use File::stat;

while(<>){
 if(($_ cmp "\n") == 0){
   exit 0;
 }
 else{
   my $file_size =  stat($_)->size; # $filesize = s $_;
   print $file_size;
 }
}

I get no output when using file test operator -s and I get errors when using stat module: 使用文件测试运算符-s时没有输出,使用stat模块时出现错误:

Unsuccessful stat on filename containing newline at /usr/share/perl/5.10/File/stat.pm line 49, <> line 1.
Can't call method "size" on an undefined value at 2.pl line 17, <> line 1.

1.txt is the filename I'm giving as an input. 1.txt是我输入的文件名。

#!/usr/bin/perl 

for (@ARGV){
  my $file_size = -s $_;
  print $file_size;
}

or similar cmd oneliner, 或类似的cmd oneliner,

perl -E 'say "$_, size: ", -s for @ARGV' *
#!/usr/bin/perl -w

$filename = '/path/to/your/file.doc';
$filesize = -s $filename;
print $filesize; 

Simple enough, right? 很简单,对不对? First you create a string that contains the path to the file that you want to test, then you use the -s File Test Operator on it. 首先,创建一个字符串,其中包含要测试的文件的路径,然后在其上使用-s File Test Operator。 You could easily shorten this to one line using simply: 您可以使用以下命令轻松地将其缩短为一行:

print -s '/path/to/your/file.doc';

Also, keep in mind that this will always return true if a file is larger than zero bytes, but will be false if the file size is zero. 另外,请记住,如果文件大于零字节,它将始终返回true,但是如果文件大小为零,则将返回false。 It makes a handy and quick way to check for zero byte files. 它是检查零字节文件的便捷方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM