我编写了一个 PowerShell 脚本,可生成 100 个带有随机时间戳的文件:
$date_min = get-date -year 1989 -month 7 -day 4
$date_max = get-date
for( $i = 0; $i -le 100; $i++ )
{
$file = $i.ToString() + ".txt"
echo ">=|" > $file
$a = get-item $file
$time = new-object datetime( get-random -min $date_min.ticks -max $date_max.ticks)
$a.CreationTime = $time
$a.LastWriteTime = $time
$a.LastAccessTime = $time
}
使用 Perl,我尝试根据上次修改时间对这些文件进行排序,如下所示:
use strict;
use warnings;
my $dir = "TEST_DIR";
my @files;
opendir( DIR , $dir ) or die $!;
# Grab all the files in a directory
while( my $file = readdir(DIR) )
{
next if(-d $file); # If the "file" is actually a directory, skip it
push( @files , $file );
}
my @sorted_files = sort { -M $b <=> -M $a } @files; # Sort files from oldest to newest
但是,当我运行代码时,我得到:
Use of uninitialized value in numeric comparison (<=>) at .\dir.pl line 31.
现在,如果我针对不是使用 powershell 脚本随机生成的文件尝试此代码,它会正常工作。我很难弄清楚为什么它不适用于这些随机生成的文件。我做错了什么吗?
最佳答案
您的问题是readdir(DIR)
。这会生成相对于指定目录的文件列表。首先尝试将 $dir
添加到文件中:
sort { -M $b <=> -M $a } map { "$dir\\$_" } @files
这也意味着您过滤目录的尝试是错误的。您可以将所有调用组合在一起,如下所示:
my @sorted_files = sort { -M $b <=> -M $a }
grep { ! -d $_ } # Removes directories
map { "$dir\\$_" } # Adds full path
readdir(DIR); # Read entire directory content at once
关于Perl -M 标志,未初始化的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19841853/