【问题标题】:How to set priority while reading multiple files in Perl如何在 Perl 中读取多个文件时设置优先级
【发布时间】:2022-10-13 22:02:59
【问题描述】:

脚本正在从输入目录中读取文件,因为我们有 5 个不同的文件。我正在尝试在处理文件时设置文件的优先级。

opendir ( INPUT_DIR, $ENV{INPUT_DIR} ) ||  die "Error in opening dir $ENV{INPUT_DIR}";
my @input_files = grep {!/^\./}  readdir(INPUT_DIR);
foreach my $input_file (@input_files) 
{
  if($input_file =~ m/^$proc_mask}$/i) 
  {
     # processing files
  }
}

就像我有 5 个文件

Creation.txt
Creation_extra.txt
Modify.txt
Modify_add.txt
Delete.txt

现在,一旦我们读取了这些输入文件,我想设置优先处理第一个 Creation_extra.txt 文件,然后处理 Delete.txt。

我无法设置文件读取的优先级然后处理它

【问题讨论】:

  • “设置优先级”是什么意思?你的意思是文件的顺序?
  • 否基于我要设置优先级的文件名。文件需要按顺序处理,这就是我尝试设置优先级的原因
  • 好吧,你有一个数组中的文件名。为了首先处理某些文件,您必须首先知道文件名。然后我会说你必须使用哈希以数字形式设置优先级,并基于 1)优先级,2)字母排序。

标签: perl


【解决方案1】:

如果我理解正确,您希望能够指出一些应在其他文件之前处理的高优先级文件名。这里有一个方法:

use strict;
use warnings;
use feature 'say';

my @files = <DATA>;   # simulate reading dir
chomp @files;         # remove newlines
my %prio;
@prio{ @files } = (0) x @files;    # set default prio = 0
my @high_prio = qw(Creation_extra.txt Delete.txt);   # high prio list

# to set high prio we only want existing files
for (@high_prio) {
    if (exists $prio{$_}) {  # check if file name exists
        $prio{$_} = 1;       # set prio
    }
}

# now process files by sorting by prio, or alphabetical if same prio
for (sort { $prio{$b} <=> $prio{$a} || $a cmp $b } @files) {
    say;
}

__DATA__
Creation.txt
Creation_extra.txt
Modify.txt
Modify_add.txt
Delete.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多