简体   繁体   中英

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

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 $!;

Also here is some code that will do such task:

#...
my ($lastfile, $data) = pop @FILES;

for (@FILES) {
    open my $fh, "<$_" or die "$!";
    $data .= join '', <$fh> , "\n"; # you can change the "\n" delimiter
    close $fh
}
open my $fh, '+<',$lastfile or die "$!";
$data .= join '', <$fh>;
seek $fh, 0, 0; # allows to write from the beginning (in this case re-write file)
print $fh $data;
close $fh; 

Read here about opening file handles in both read and write mode.
Also take care about which delimiter you use to make the result file more readable.


EDIT
You can even do so:

$data .= "$_ -> " . join '', <$fh> , "\n";

in first join and

$data .= "$lastfile -> " . join '', <$fh>;

in second if you want to remember what content was in each file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM