Tomb Tomb - 6 months ago 9
Perl Question

open multiple files and copy their content to the last file opened

I'd like to open multiple files and copy their content to the last file opened

input:

file1.txt -> 1111
file2.txt -> 2222
file3.txt -> 3333


output should be:

file1.txt -> 1111
file2.txt -> 2222
file3.txt -> 1111 2222 3333


my code

#!/usr/bin/perl
use strict;
use warnings;

my %data;
my @FILES = @ARGV;

foreach my $file (@FILES) {
local $/ = undef;
open my $fh, '<', $file;
$data{$file} = <$fh>;

foreach my $key (keys %data) {
open (OUTFILE, ">".$file) or die "#!\n";
print OUTFILE "$key";
}
}
close(OUTFILE);
exit;


output from the code:

file1.txt -> file1.txt
file2.txt -> file1.txt
file3.txt -> file3.txt


It's not reading the files because it prints the file name instead of it's content and also I can't seem to print the content of previous files into the last file.
Thanks in advance

Answer

You need to write to a different file, otherwise you'd rewrite the last file before reading its contents. You can then write to the output directly when reading the files, no need to store the contents in a hash. If you want to use the hash, print the values, not the keys.

#!/usr/bin/perl
use warnings;
use strict;

my $output_file = $ARGV[-1];
my $tmp = $output_file . "-tmp$$";

open my $OUT, '>', $tmp or die $!;

while (<>) {
    print {$OUT} $_;
}

rename $tmp, $output_file or die $!;
close $OUT or die $!;