cal has asked for the wisdom of the Perl Monks concerning the following question:

Hello,
Does anyone know how I could open,read a file while opening,writing to another file at the same time.
I need to reformat and store the same data.
Thanks

Replies are listed 'Best First'.
Re: writing files while reading files
by perigeeV (Hermit) on Jul 21, 2002 at 02:03 UTC

    open(READER, "file1") || die "$!"; open(WRITER, "+<file2") || die "$!"; while(<READER>) { chomp; munge($_); mutilate($_); print WRITER "$_\n"; # Note the filehandle argument to print. }


Re: writing files while reading files
by dpuu (Chaplain) on Jul 21, 2002 at 02:06 UTC
    Simply open the files and use them (its best to open the input file first: if there's an error opening it, you don't want to create the output file).
    sub convert { scalar reverse shift } # whatever my $infile = "infile.txt"; my $outfile = "outfile.txt"; open IN, "<$infile" or die "can't read $infile: $!"; open OUT, ">$outfile" or die "can't write $outfile: $!"; while (<IN>) { print OUT convert($_); } close OUT; close IN;
    If you're doing only simple conversions, then you don't need to put the formating in a subroutine; but it doesn't do any harm. --Dave.
Re: writing files while reading files
by flounder99 (Friar) on Jul 22, 2002 at 02:11 UTC
    One other thing should be mentioned is the -i command line switch. It specifies that using <> operator will edit files in place with an optional extension to rename the input file. See perlrun for the details.

    --

    flounder