Beefy Boxes and Bandwidth Generously Provided by pair Networks vroom
Syntactic Confectionery Delight
 
PerlMonks  

Re: How do I join two files side by side?

by Mago (Parson)
on Dec 13, 2004 at 15:15 UTC ( [id://414529]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


in reply to How do I join two files side by side?

#!/usr/bin/perl -w use strict; my ($string1, $string2); $/ = undef; open (FILE1, "< x") || die "Cannot open file : $!"; open (FILE2, "< y") || die "Cannot open file : $!"; open (FILE3, "> z") || die "Cannot open file : $!"; $string1 = <FILE1>; $string2 = <FILE2>; print FILE3 join('', $string1, $string2); close (FILE1); close (FILE2); close (FILE3);

Replies are listed 'Best First'.
Re: Answer: How do I join two files?
by Joost (Canon) on Dec 13, 2004 at 15:41 UTC
    That code will in fact only cat the first line of file x and the first line of file y.

    I wouldn't even use perl for this, but if you must:

    #!/usr/bin/perl -w use strict; my ($string1, $string2); # read files in chunks instead of lines # remove if you realy want to read textfiles # line by line local $/ = \32768; # "block size" open (FILE1, "< x") || die "Cannot open file : $!"; open (FILE2, "< y") || die "Cannot open file : $!"; open (FILE3, "> z") || die "Cannot open file : $!"; # set binmode, so binary files don't get messed # up on systems with text/binary mode files # (like windows or MS-DOS) binmode (FILE1); binmode (FILE2); binmode (FILE3); print FILE3 <FILE1>,<FILE2> or die "Error concatenating: $!"; close FILE1 or die "Error closing x: $!"; close FILE2 or die "Error closing y: $!"; close FILE3 or die "Error closing z: $!";

    update: fixed copy/paste error

Re: Answer: How do I join two files?
by Mago (Parson) on Dec 14, 2004 at 05:31 UTC

    Copy and Paste Error !

    Correct Code:

    #!/usr/bin/perl -w use strict; my ($string1, $string2); $/ = undef; open (FILE1, "< x") || die "Cannot open file : $!"; open (FILE2, "< y") || die "Cannot open file : $!"; open (FILE3, "> z") || die "Cannot open file : $!"; $string1 = <FILE1>; $string2 = <FILE2>; print FILE3 join('', $string1, $string2); close (FILE1); close (FILE2); close (FILE3);
      Updated your answer; does it look ok now? Please /msg QandAEditors if you need changes made.
        How do I change my answer ?

        QandAEditors Request !

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://414529]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.