I am doing the below steps:
- Read all the text files in a directory and store it in an array named @files
- Run a foreach loop on each text file.
Extract the file name(stripping of .txt) using split operation and creating a folder of that particular filename.
Rename that file to Test.txt (so as to work as input fo another perl executable)
Executing test.pl for each file by adding the line require “test.pl”;
It works fine for only one file, but not any more.
Here is my code:
opendir DIR, ".";
my @files = grep {/\.txt/} readdir DIR;
foreach my $files (@files) {
@fn = split '\.', $files;
mkdir "$fn[0]"
or die "Unable to create $fn[0] directory <$!>\n";
rename "$files", "Test.txt";
require "test3.pl";
rename "Test.txt", "$files";
system "move $files $fn[0]";
}
Any help would be very grateful.
The
requirefunction trys to be smart and load the code only if it isn’t already loaded. Why is this great? (1.) We don’t have C’s preprocessor hell with conditional includes, and (2.) we save time.To execute another perl script, we have a variety of possibilites. The one that you probably want, is
doing a script. Thedo FILENAMEsyntax is just like eval, except that your scope isn’t visible to thedone file.You could also start another interpreter via
system "./test3.pl".You could make
test3.pla module, e.g. withpackage test3;, and pack the contents into asub. Instead of hardcoding a filename, you would probably pass the current filename as an argument. This is not only better coding practice, but allows you to scale your application more easily, e.g. going multithreaded.Here is how I’d implement that snippet:
Interesting side points:
globis great, works just as in the shell.Always use
myfor variables, unless you have a really good reason.I further assume that the file
text.en.txtshould not create the directorytext, buttext.en, and that the file.txtdoes not exist.Whether this does or doesn’t work also depends on the script you are calling.