Search code examples
perlloopsfile-iodir

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

Solution

  • "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.