#!perl
# Append contents of $appendfile to $targetfile in each subdirectory of $maindir.
use strict;
use warnings;
use File::Copy;
use Cwd qw(chdir getcwd);
# $targetfile: name of file to append to
# $appendfile: file whose contents we're appending to $targetfile
# $maindir (optional): name of main directory in which $appendfile will be found
# and in whose subdirectories $targetfile will be found.
# If $maindir is not specified, it's assumed to be the current directory.
my ($targetfile, $appendfile, $maindir) = (shift, shift, shift);
die qq(\$targetfile and \$appendfile must be specified on command line.\n)
unless $targetfile && $appendfile;
# chdir to $maindir unless we're already there
my $thisdir = getcwd;
$maindir ||= $thisdir;
unless ($maindir eq $thisdir) {
chdir $maindir || die qq(Can't chdir to "$maindir".\n);
}
$thisdir = getcwd;
# Get contents of $appendfile
open(APPENDFILE, $appendfile) ||
die qq(Can't open append file "${maindir}/$appendfile" for read.\n);
my @append = <APPENDFILE>;
opendir(MAINDIR, "$thisdir") || die qq(Can't open "$thisdir".\n);
while (my $dir = readdir(MAINDIR)) {
next if ($dir eq ".") || ($dir eq "..");
next unless -d $dir;
unless (open(TARGET, "${dir}/$targetfile")) {
warn qq(Can't open target file "${dir}/$targetfile" for read.\n);
next;
}
my @target = <TARGET>;
unless (close(TARGET)) {
warn qq(Can't close target file "${dir}/$targetfile" after reading.\n);
next;
}
# Make backup copy of $targetfile, named $targetfile.bak
# NOTE: File::Copy and File::Move return 1 for success, 0 for failure!
my $result = copy("${dir}/$targetfile", "${dir}/${targetfile}.bak");
unless ($result) {
warn qq(Couldn't copy "${dir}/$targetfile" to "${dir}/${targetfile}.bak".\n);
next;
}
unless (open(TARGET, ">${dir}/$targetfile")) {
warn qq(Can't open target file "${dir}/$targetfile" for write.\n);
next;
}
# Write out original contents of $targetfile followed by $appendfile,
# overwriting original $targetfile
print TARGET (@target, @append);
unless (close(TARGET)) {
warn qq(Can't close target file "${dir}/$targetfile" after writing.\n);
next;
}
}
closedir(MAINDIR) || die qq(Couldn't close "$thisdir".\n);
__END__