Одно из возможных решений
use autodie
для автоматической обработки ошибок открытия / закрытия
- Файл :: Spec для обработки имени пути
- читать исходный файл как двоичный файл, используя File :: Slurper
- открыть файл назначения для добавления в двоичный файл
- с использованием современной версии с тремя аргументами
open()
- печать содержимого в дескриптор файла назначения
#!/usr/bin/perl
use warnings;
use strict;
use autodie;
use File::Spec;
use File::Slurper qw(read_binary);
my $source_dir = "tmp/source_dir";
my $dest_dir = "tmp/dest_dir";
opendir(my $source, $source_dir);
foreach my $file (readdir $source) {
unless ($file =~ /^\.\.?$/) {
my $content = read_binary(File::Spec->catfile($source_dir, $file));
open(my $ofh, '>> :raw :bytes', File::Spec->catfile($dest_dir, $file));
print $ofh $content;
close($ofh);
}
}
closedir($source);
exit 0;
Тестовый прогон:
$ ls -lhtR tmp/
...
tmp/dest_dir:
-rw-rw-r--. 1 stefanb stefanb 33 22. 3. 20:32 1.bin
-rw-rw-r--. 1 stefanb stefanb 27 22. 3. 20:32 2.bin
-rw-rw-r--. 1 stefanb stefanb 15 22. 3. 20:32 3.bin
tmp/source_dir:
-rw-rw-r--. 1 stefanb stefanb 11 22. 3. 20:32 1.bin
-rw-rw-r--. 1 stefanb stefanb 9 22. 3. 20:32 2.bin
-rw-rw-r--. 1 stefanb stefanb 5 22. 3. 20:31 3.bin
$ perl dummy.pl
$ ls -lhtR tmp/
...
tmp/dest_dir:
-rw-rw-r--. 1 stefanb stefanb 44 22. 3. 20:34 1.bin
-rw-rw-r--. 1 stefanb stefanb 36 22. 3. 20:34 2.bin
-rw-rw-r--. 1 stefanb stefanb 20 22. 3. 20:34 3.bin
tmp/source_dir:
-rw-rw-r--. 1 stefanb stefanb 11 22. 3. 20:32 1.bin
-rw-rw-r--. 1 stefanb stefanb 9 22. 3. 20:32 2.bin
-rw-rw-r--. 1 stefanb stefanb 5 22. 3. 20:31 3.bin
ОБНОВЛЕНИЕ: ОП изменил требования, добавляя их только в том случае, если файл назначения существует. Блок unless
будет выглядеть следующим образом:
my $dest_file = File::Spec->catfile($dest_dir, $file);
# only append if destination file exists
if (-f $dest_file ) {
my $source_file = File::Spec->catfile($source_dir, $file);
my $content = read_binary($source_file);
open(my $ofh, '>> :raw :bytes', $dest_file);
print "Appending contents of ${source_file} to ${dest_file}\n";
print $ofh $content;
close($ofh);
}