简体   繁体   中英

Loop through file with similar names

How can I loop through files with similar names? This script works just for the first line of the first file and I don't understand the reason. Is there a simpler way to do it? This script has been created in order to read files, and write in another file all lines without numbers inside.

use Data::Dumper;
use utf8;
#read OUT_AM3.txt, OUT_MOV3.txt, OUT_TA3.txt

opendir (DIR, '.') or die "Couldn't open directory, $!";
my @files = readdir(DIR);
closedir DIR;

$out = "Res.txt";
open (O, ">>", $out);
binmode(O, "utf8");

@eti = ("AM3","TA3","MOV3");
for ($i = 0; $i < @eti; $i++){
      foreach $fh(@files){
            open($fh, "<", "OUT_$eti[$i].txt");
            binmode($fh, "utf8");

            while(defined($l = <$fh>)){
                if (!grep /\-?\d\.\d+/, $l){
                print O $l;
            }
        }
    }
}

You don't need

for ($i = 0; $i < @eti; $i++)

as it will loop three times over all files found in directory.

Also, when looping over @files it is expected to use array elements,

  foreach my $file (@files) {
     -f $file or next;

     open(my $fh, "<", $file) or die $!;
     # ..
  }

"But it's not very important the result. I would like know how to open each file in the directory without writing always the name of the file. "

If I understand you correctly, you might want this?

my @files = grep /OUT_.*/, glob("*");
print $_ . "\n" foreach @files;

Or if you don't mind using module. There is File::Find::Rule

use File::Find::Rule;
my $rule =  File::Find::Rule->new;
$rule->file;
$rule->name( 'OUT_*' );
my @files = $rule->in( "." );

Both will give a list of file name in @files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM