sorting - 在 Perl 版本 5.20 中从具有可选排序的 sub 返回 arrayref 的适当方法

标签 sorting perl subroutine arrayref

我尝试在 Perl 5 版本 5.20 下编写一个子例程,它创建一个存储在数组中的大目录列表。子例程将结果作为 arrayref 返回。出于方便原因,我希望可以选择对结果进行排序。

#!/usr/bin/env perl
use v5.20;
use warnings;
use strict;
use File::Slurp qw(read_dir);
use Time::HiRes;

use feature qw(signatures);
no warnings 'once';
no warnings 'experimental';
no warnings 'experimental::signatures';

my $PATH='/net/dbfs/GRM-RS/Flight-Campaigns/2021-08-23.Ram-Head-i-22.SE-01/cam/MM010259/iiq/';


sub fsReadDir($base, $sort, $mode = 1) {
    $base    //= '.';         # Base path default is the current path
    $sort    //= 0;           # Flag for array sorting of the result 
    my @res=read_dir($base);
    if ($sort) {
       return [sort(@res)] if $mode == 1;
       if ($mode == 2)  {
           @res = sort(@res);
           return \@res;
       }
    } else {  
        return \@res;
    } 
}

sub testSorting($sort, $mode, $max = 1000) {
    my $start = [Time::HiRes::gettimeofday()];   
    my $count = 0;
    for my $ix (0..$max) {
        my $array = fsReadDir($PATH, $sort, $mode );
        $count = @$array;
    }
    my $end   = time();
    my $dif = Time::HiRes::tv_interval($start);
    print "SORT: $sort MODE: $mode COUNT: $count TIME: $dif s\n"
}

testSorting(0, 1);
testSorting(1, 1);
testSorting(1, 2);

结果

/usr/bin/env perl "test-array.pl"
SORT: 0 MODE: 1 COUNT: 14861 TIME: 6.882694 s
SORT: 1 MODE: 1 COUNT: 14861 TIME: 9.131504 s
SORT: 1 MODE: 2 COUNT: 14861 TIME: 8.622628 s

直接在返回级别对数组进行排序的有效方法是什么?

最佳答案

如果坚持要在return语句本身进行排序业务可以使用三元

return $sort ? [ sort @res ] : \@res;

在简单的情况下,这可能已经足够清楚了。

但是,我发现先处理案例和选项,然后返回结果会更清晰

@res = sort @res if $sort;

if    ($mode == 1) { ... }   # modes given in the question do nearly the same,
elsif ($mode == 2) { ... }   # but imagine different processing based on value
...

return \@res;

此外,就地排序应该会更高效一些。

如果这与效率有关,那么您需要在现实情况下对不同的方法进行基准测试。其一,当人们可能无法分辨出返回值的构造方式有何性能差异时,通过阅读一个大目录,一切都可能会被打乱。

所以我会尽量澄清,直到清楚地看到该选择确实会影响性能。

关于sorting - 在 Perl 版本 5.20 中从具有可选排序的 sub 返回 arrayref 的适当方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70700055/

相关文章:

python - 合并三个排序列表的递归 Python 程序

scala - 如何对 List[Int] 对象进行排序?

c - 删除排序数组中的 double ,然后将 X 放在最后

perl 脚本检查是否安装了 perl 模块

perl - 如何将可选参数传递给 Perl 函数?

c - C语言中如何打印子程序的输出?

c - 按升序对堆栈进行排序?

perl - 使用 XML::TWIG 解析大型 xml 文件失败

perl - 为什么我的 continue 在 Perl 5.10 中不执行下一个 when block ?

batch-file - 从子程序中获取批处理文件名