无法从其目录列表中获取文件的大小

时间:2018-10-10 10:05:30

标签: perl

我目前正在尝试获取目录列表中所有文件的大小(忽略任何子目录)。我正在使用opendirreaddir操作,对于每个文件,我都将名称和大小输出到文件中。正确输出了文件名,但没有输出大小。我已经使用-s运算符和stat内置函数进行了尝试,但同时收到警告,提示该值未初始化。

我的代码是:

   #!/usr/bin/perl

    use strict;
    use warnings;

    my $dir = $ARGV[0];

    opendir(DIR, $dir) or die "Could not open directory '$dir' $!";

    my $filename = 'FileSize.txt';
    open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";

    while (my $file = readdir(DIR)) {

        # Ignore Sub-Directories
        next unless (-f "$dir/$file");
        my $size = -s $file;
        print $fh "$file"," ","$size\n";

    }

    closedir(DIR);
    exit 0;

我从顶层目录本身运行命令,包括要扫描的子目录的名称,并得到以下错误,该错误对应于处理的子目录中的每个文件

C:\Users\lafarnum\Documents>perl FileComp.pl DiskImage
Use of uninitialized value $size in concatenation (.) or string at 
FileComp.pl line 18.

因此,文件名会正确输出到输出文件,但不会输出到文件大小。输出文件看起来像这样

BuildState.txt
data1.cab 
data1.hdr 
data2.cab 
ISSetup.dll 
layout.bin 
README.doc 
setup.bmp
setup.exe 
setup.ini 
setup.inx 
setup.iss 
vcredist_x86.exe 
_Setup.dll 

我认为这与我从readdir检索文件变量的方式有关。使用-s运算符和stat内置函数的所有示例都是在用户对文件名进行硬编码而不是使用readdir来获取文件时。我是使用Perl的新手,如果我犯了一个基本错误,请您道歉。

2 个答案:

答案 0 :(得分:2)

(由@tinita指出)文件测试操作符需要文件的相对或绝对路径,而readdir将仅返回文件的基本名称,因此您需要将要迭代的目录与基本名称连接在一起获取文件路径。

my $size = -s "$dir/$file";

有趣的是,使用Path::Tiny时,此脚本的外观如下:

use strict;
use warnings;
use Path::Tiny;

my $dir = $ARGV[0];

my $fh = path('FileSize.txt')->openw;

foreach my $file (grep { -f } path($dir)->children) {
    my $basename = $file->basename;
    my $size = -s $file;
    print $fh "$basename $size\n";
}

答案 1 :(得分:0)

类似下面一种衬里的东西会起作用。

/usr/libexec> \ls -1 | perl -ne '  while (<>) {chop($_); $size= -s "$_"; print "$size, $_\n" if not -d $_ } '
96168, gam_server
18808, gnupg-pcsc-wrapper
52232, gpg2keys_curl
61120, gpg2keys_finger
60888, gpg2keys_hkp
66432, gpg2keys_ldap
100344, gpg-check-pattern
85616, gpg-preset-passphrase
210416, gpg-protect-tool
21096, hald-addon-acpi
22352, hald-addon-generic-backlight
24136, hald-addon-hid-ups
17328, hald-addon-imac-backlight
31448, hald-addon-input
22776, hald-addon-ipw-killswitch
26224, hald-addon-leds
22384, hald-addon-macbook-backlight
22672, hald-addon-macbookpro-backlight