in reply to Use 2 files and print each line of each one side-by-side

Just for the fun, a HOP version using closures and function factories. First a long explanatory version:
use strict; use warnings; my $file1 = make_func (shift); my $file2 = make_func (shift); while (1) { my $line1 = $file1->(); my $line2 = $file2->(); last unless defined $line1 and defined $line2; print "$line1 $line2 \n"; } sub make_func { my $file = shift; open my $FH, "<", $file or die "could not open $file $!"; return sub {my $c = <$FH>; return unless defined $c; chomp $c; return $c } }
And now a more concise form:
use strict; use warnings; my $file1 = make_func (shift); my $file2 = make_func (shift); my ($line1, $line2); chomp $line1 and print $line1, $line2 while ($line1 = $file1->() and $ +line2 = $file2->()); sub make_func { my $file = shift; open my $FH, "<", $file or die "could not open $file $!"; sub {<$FH>; } }
It can probably be made more concise, but I have no time right now.

Replies are listed 'Best First'.
Re^2: Use 2 files and print each line of each one side-by-side
by Util (Priest) on Feb 19, 2014 at 03:40 UTC

    Also for fun, a Perl 6 version.
    Note that this only works for files of the same length, because Z terminates (without error) when the shorter list ends.

    use v6; sub MAIN ( $in_path1, $in_path2, $out_path = 'CONCATENATED_FILES' ) { my $in1 = open $in_path1, :r; my $in2 = open $in_path2, :r; my $out = open $out_path, :w; for $in1.lines Z $in2.lines -> $line1, $line2 { $out.say: "$line1\t$line2"; } .close for $out, $in1, $in2; }