Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: writing two files (different in length) to one output

by hippo (Bishop)
on May 28, 2017 at 11:27 UTC ( [id://1191420]=note: print w/replies, xml ) Need Help??


in reply to writing two files (different in length) to one output

If one input file is shorter than the other, it should return to the first line, which is the difficulty to me.

If you store the input files as arrays then it is less tricky:

#!/usr/bin/env perl #===================================================================== +========== # # FILE: zip.pl # # USAGE: ./zip.pl input1 input2 output # # DESCRIPTION: Zip 2 input files into one output file, looping the # shorter one. # # REQUIREMENTS: Path::Tiny # NOTES: See http://www.perlmonks.org/?node_id=1191418 #===================================================================== +========== use strict; use warnings; use Path::Tiny; my @in = ( path ($ARGV[0]), path ($ARGV[1]) ); my $out = $ARGV[2]; my @first = $in[0]->lines; my @second = $in[1]->lines; my $max = $#first > $#second ? $#first : $#second; open my $outfh, '>', $out or die "Cannot open $out for writing: $!"; for (0 .. $max) { print $outfh $first[$_ % @first] . $second[$_ % @second] }

Bad argument trapping is left as an exercise.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1191420]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2024-04-16 19:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found