Home > Software engineering >  How to set priority while reading multiple files in Perl
How to set priority while reading multiple files in Perl

Time:10-13

Script is reading files from a input directory in that we have 5 different files . I am trying to set priority on the files while I am processing it.

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
  }
}

Like I have 5 files

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

Now once we read these input files I want to set priority that first Creation_extra.txt files is processed and then Delete.txt is processed.

I am not able to set priority on the files reading and then processing it

CodePudding user response:

If I understand you correctly, you want to be able to point out some high priority file names that should be processed before other files. Here's a way:

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
  •  Tags:  
  • perl
  • Related