G'day ic23oluk,
Here's my take on a solution (pm_1191418_file_merge.pl):
#!/usr/bin/env perl -l use strict; use warnings; use autodie; die "Usage: $0 file1 file2\n" unless @ARGV == 2; my (@fhs, $shorter); for (@ARGV) { die "'$_' is zero-length\n" if -z; open my $fh, '<', $_; push @fhs, $fh; } LOOP: while (1) { my @out_line; for (0 .. 1) { my $line = readline $fhs[$_]; if (! defined $line) { $shorter = $_ unless defined $shorter; last LOOP if $shorter != $_; seek $fhs[$_], 0, 0; $line = readline $fhs[$_]; } push @out_line, $line; } chomp @out_line; print @out_line; }
I created four input files: one empty; one with just a single newline; the other two with data.
$ ls -al pm_1191418_data_* -rw-r--r-- 1 ken staff 1 May 29 16:57 pm_1191418_data_blank.txt -rw-r--r-- 1 ken staff 24 May 29 16:14 pm_1191418_data_five.txt -rw-r--r-- 1 ken staff 8 May 29 16:14 pm_1191418_data_two.txt -rw-r--r-- 1 ken staff 0 May 29 16:47 pm_1191418_data_zero.txt $ cat pm_1191418_data_zero.txt $ cat pm_1191418_data_blank.txt $ cat pm_1191418_data_two.txt ONE TWO $ cat pm_1191418_data_five.txt one two three four five
These first two runs just exercise the sanity tests:
$ pm_1191418_file_merge.pl Usage: ./pm_1191418_file_merge.pl file1 file2 $ pm_1191418_file_merge.pl pm_1191418_data_zero.txt pm_1191418_data_tw +o.txt 'pm_1191418_data_zero.txt' is zero-length
The remaining runs test blank lines; files with a different number of lines in either order; and files with the same number of lines:
$ pm_1191418_file_merge.pl pm_1191418_data_blank.txt pm_1191418_data_t +wo.txt ONE TWO $ pm_1191418_file_merge.pl pm_1191418_data_two.txt pm_1191418_data_bla +nk.txt ONE TWO $ pm_1191418_file_merge.pl pm_1191418_data_two.txt pm_1191418_data_fiv +e.txt ONEone TWOtwo ONEthree TWOfour ONEfive $ pm_1191418_file_merge.pl pm_1191418_data_five.txt pm_1191418_data_tw +o.txt oneONE twoTWO threeONE fourTWO fiveONE $ pm_1191418_file_merge.pl pm_1191418_data_blank.txt pm_1191418_data_b +lank.txt $ pm_1191418_file_merge.pl pm_1191418_data_two.txt pm_1191418_data_two +.txt ONEONE TWOTWO
— Ken
In reply to Re: writing two files (different in length) to one output
by kcott
in thread writing two files (different in length) to one output
by ic23oluk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |