I am very new to Perl and I need to write a Perl script to do the following:
- Traverse a directory recursively and only process files with a specific extension (e.g .txt).
- For each .txt files, I need to either prepend a header to the file or update the header if the header already exists.
The header looks something like this:
//-----------------------------------------//
Model : Info1
Date : Info2
Name : Info3
//-----------------------------------------//
What I have done so far:
use File::Find;
use Cwd qw(getcwd);
use strict;
sub gen_header {
my $divider = "//------------------------------------//\n";
my $time = localtime();
my $modelpath = getcwd();
my $user = (getpwuid($<))[0];
my $header;
$header .= $divider;
$header .= "//Model : $modelpath\n";
$header .= "//Date : $time\n";
$header .= "//Name : $user\n";
$header .= $divider;
$header .= "\n";
return header;
}
my $dir = "/src/dir1";
find (\&process_file, $dir);
sub process_file {
my $filename = $_;
my $out_file = $_.out;
if (-f and /\.(txt)$/) {
open (my $fh1, "<", $filename) || die "ERROR";
open (my $fh2, ">", $out_file) || die "ERROR";
if (*header already exist*) {
#Update header
*code to update Info1, Info2 and Info3 in the header;*
} else {
#Prepend the header
print $fh2 gen_header();
while (<$fh1>) {
print $fh2 $_;
}
}
close $fh2;
rename ($out_file, $filename) or die "Rename error";
}
}
I have managed to create a subroutine to generate the header required and I'd like to believe that the way I am traversing the directory recursively and processing the files is correct. Though, I am having trouble figuring out how to update the header after that. So question,
- How do I do the "update header" part of the code? The gen_header subroutine returns a new header with the latest info every time its run but how do I use it to replace the old header?
- Is the way I am traversing a directory recursively and processing files correct or is there a better way to do what I want?