Perl -M 标志,未初始化的值?

标签 perl powershell initialization comparison 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
}

使用 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/

相关文章:

C++ - 继承和初始化问题

bash - 将 2 行组合在一起但 "interlaced"

internet-explorer - 关于 $ie.Document.getElementById

powershell - 我们如何在终端中处理 Visual Studio Code 中的问题

powershell - 如何通过powershell添加Azure应用服务扩展?

javascript - 如何执行一个js函数onload?

c++ - Eclipse 中的奇怪错误

json - 如何在 Perl 中合并两个复杂的数据结构?

perl - 在 mojolicious 响应中设置 cookie

perl - 我想在 Perl 中对数组数组进行排序,但结果没有排序