ozzy
ozzy

Reputation: 13

How to extend a program that works for one file to act on every file in a directory

I wrote a program to check for misspellings or unused data in a text file. Now, I want to check all files in a directory using the same process.

Here are a few lines of the script that I run for the first file:

open MYFILE, 'checking1.txt' or die $!;
@arr_file = <MYFILE>;
close (MYFILE);

open FILE_1, '>text1' or die $!;
open FILE_2, '>Output' or die $!;
open FILE_3, '>Output2' or die $!;
open FILE_4, '>text2' or die $!;

for ($i = 0; $i <= $#arr_file; $i++) {

    if ( $arr_file[$i-1] =~  /\s+\S+\_name\s+ (\S+)\;/ ) {
           print FILE_1 "name : $i  $1\n";
    }

...

I used only one file, checking1.txt, to execute the script, but now I want to do the same process for all files in the all_file_directory

Upvotes: 0

Views: 97

Answers (3)

yoniyes
yoniyes

Reputation: 1030

  1. Why not useFile::Find? Makes changing files in directories very easy. Just supply the start directory. It's not always the best choice, depends on your needs, but it's useful and easy almost every time I need to modify a lot of files all at once.

  2. Another option is to just loop through the files, but in this case you'll have to supply the file names.

  3. As mkHun pointed out a glob can be helpful.

Upvotes: 0

mkHun
mkHun

Reputation: 5927

Your all files in same directory means put the program inside the directory then run it.

For read the file from a directory use glob

while (my $filename =<*.txt>) # change the file extension whatever you want
{

    open my $fh, "<" , $filename or die "Error opening $!\n";

    #do your stuff here

}

Upvotes: 2

Chankey Pathak
Chankey Pathak

Reputation: 21676

Use an array to store file names and then loop over them. At the end of loop rename output files or copy them somewhere so that they do not get overwritten in next iteration.

my @files = qw(checking1.txt checking2.txt checking3.txt checking4.txt checking5.txt);
foreach my $filename (@files){
    open (my $fh, "<", $filename) or die $!;
    #perform operations on $filename using filehandle $fh
    #rename output files    
}

Now for the above to work you need to make sure the files are in the same directory. If not then:

  • Provide absolute path to each file in @files array
  • Traverse directory to find desired files

If you want to traverse the directory then see:

Also:

and give proper names to the variables. For eg:

@arr_file = <MYFILE>;

should be written as

@lines = <MYFILE>;

Upvotes: 2

Related Questions