Re: Use 2 files and print each line of each one side-by-sideby Kenosis (Priest)
|on Feb 18, 2014 at 19:05 UTC||Need Help??|
Always, and without fail, include the following at the top of your Perl scripts:
These pragmas will likely save you many headaches by showing you problematic areas in your script.
Use the three-argument form of open. For example:
Note also the use of $!. It's good that you're handling errors; it's better if you're shown exactly what produced an exception if there's an error, and $! will let you know.
You need to do the same when opening a file for writing. However, you can do the just following when opening files:
if you include the following pragma:
Looping through both files is a good way to achieve your desired results, and roboticus provided a solution for handling reading from both files. Since, however, your running this script from the command line, here's another option--in case you may be interested:
Usage: perl script.pl file1 file2 >combinedFile
The script uses File::Slurp to read each file's contents into an array. Next, is uses List::MoreUtils to 'zip' or interleave the elements of the two arrays. When iterating through the arrays for printing, the script checks that both elements are defined in case one file has more lines than the other.
The above script will work just fine with small or not-too-large files, since their entire contents are read into arrays. If, however, your files are large, stick with just iterating through each file, a line at a time.
Hope this helps!