检查文件大小,如果文件没有增长,则移动它[readdir]

问题描述 投票:1回答:2

我首先为Windows平台制作​​了脚本并且它有效。现在我已经将脚本移动到Ubuntu并且无法使其正常工作。

读取文件大小的问题是什么?

while ( opendir my $dirh, "/share/Dropbox/test/in" ) {

    while ( my $file = readdir $dirh ) {

        # filter . & .. folders out
        next if ($file =~ m/^\./);

        my $size1 = -s $file;
        print "$size1\n";

        sleep 2;

        my $size2 = -s $file;
        print "$size2\n";

        if ( $size1 == $size2 ) {
            move( $file, "/share/Dropbox/test/out" );
        }
    }

    sleep 1;
}
closedir DIR;

我在运行时得到的警告:

在连接(。)中使用未初始化的值$ size1或在./file_ready_2.pl第20行使用字符串。

在连接(。)中使用未初始化的值$ size2或在./file_ready_2.pl第23行使用字符串。

在./file_ready_2.pl第25行的数字eq(==)中使用未初始化的值$ size2。

在./file_ready_2.pl第25行的数字eq(==)中使用未初始化的值$ size1。

在连接(。)中使用未初始化的值$ size1或在./file_ready_2.pl第20行使用字符串。

在连接(。)中使用未初始化的值$ size2或在./file_ready_2.pl第23行使用字符串。

perl
2个回答
-1
投票

问题是一个described by @AnFi。这适用于Linux(只需注释掉move行):

#!/usr/bin/perl
use strict;
use warnings;

my $dirpath = shift;    # first cmdline argument

opendir my $dirh, $dirpath
  or die "Can't opendir $dirpath: $!\n";

chdir $dirpath
  or die "Can't chdir to $dirpath: $!\n";

while ( my $file = readdir $dirh ) {

    next if $file =~ m/^\./;    # skip dotfiles
    next if not -f $file;       # skip non-files

    my $size1 = -s $file;
    print "$size1\n";
    sleep 2;
    my $size2 = -s $file;
    print "$size2\n";

    if ( $size1 == $size2 ) {

        print "moving $file\n";
        #move($file,"/share/Dropbox/test/out");
    }
}

3
投票

readdir返回的文件名是相对于opendir目录的。如果您使用另一个目录作为当前目录执行脚本,则文件测试(例如-s)将无法工作(或测试错误的文件)。

perldoc -f readdir

readdir DIRHANDLE [...]如果您计划从“readdir”中对返回值进行文件测试,则最好先添加相关目录。否则,因为我们没有“chdir”那里,它会测试错误的文件。 [...]

# FIX1 Keep directory name in variable, make it end with directory separator 
my $dir = "/share/Dropbox/test/in/";
while (opendir my $dirh, $dir ) {
    ...
    # FIX2: prepend directory name (with trailing directory separator)
    #       for size tests  
    my $size1 = -s "$dir$file";
    print "$size1\n";
    sleep 2;
    my $size2 = -s "$dir$file";
    print "$size2\n";
    ....
© www.soinside.com 2019 - 2024. All rights reserved.