http://www.perlmonks.org?node_id=924479


in reply to Merging files, 1 line for every 10

I'm with others here wondering what possible purpose this serves, but I would probably do something like the below. $in_file1 being the larger of the two files.

open($in_fh1, '<', $in_file1); open($in_fh2, '<', $in_file2); open($out_fh, '>', $out_file); while (my $line1 = <$in_fh1>) { chomp($line1); state $i; $i++; say {$out_fh} $line1; unless ($i % 10) { chomp(my $line2 = <$in_fh2>); say {$out_fh} $line2 if $line2; } }

Replies are listed 'Best First'.
Re^2: Merging files, 1 line for every 10
by trizen (Hermit) on Sep 07, 2011 at 21:59 UTC
    I'd recommend a simpler code:
    open my $in_fh1, '<', $in_file1; open my $in_fh2, '<', $in_file2; open my $out_fh, '>', $out_file; while (defined(my $line1 = <$in_fh1>)) { print {$out_fh} $line1; unless ($. % 10) { my $line = <$in_fh2>; print {$out_fh} $line; } }

      The use of $. does make things more simple. I'll have to take note of that for similar situations in the future. What is the benefit of the added defined call?

        It deals with the edge case where $line gets a value that is false before the actual end of file.

        True laziness is hard work