Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

writing files while reading files

by cal (Beadle)
on Jul 21, 2002 at 01:50 UTC ( [id://183716]=perlquestion: print w/replies, xml ) Need Help??

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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2024-04-23 21:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found