eri*_*ar7 2 powershell perl comparison initialization numeric
我编写了一个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
}
Run Code Online (Sandbox Code Playgroud)
使用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
Run Code Online (Sandbox Code Playgroud)
但是,当我运行我的代码时,我得到:
在.\ dir.pl第31行的数字比较(<=>)中使用未初始化的值.
现在,如果我对使用我的powershell脚本随机生成的文件尝试此代码,它可以正常工作.我很难搞清楚为什么它不适用于这些随机生成的文件.难道我做错了什么?
你的问题是readdir(DIR).这将生成相对于指定目录的文件列表.尝试首先添加$dir到文件:
sort { -M $b <=> -M $a } map { "$dir\\$_" } @files
Run Code Online (Sandbox Code Playgroud)
这也意味着您尝试过滤目录是错误的.您可以将所有调用组合在一起,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
158 次 |
| 最近记录: |