Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Writing to file and reading from same file

by basm100 (Novice)
on Feb 27, 2002 at 11:34 UTC ( [id://147862]=perlquestion: print w/replies, xml ) Need Help??

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

Hi, I want to know how I can open a file for both reading and writing

My script writes data to a file, and I then want to read data from that same file in the next part of my script.

I tried closing the filehandle and reopening as a read file, but it threw up the error "open for writing at line..."

Is there an easy way to open a file for both reading and writing ? Thanx,

basm100

  • Comment on Writing to file and reading from same file

Replies are listed 'Best First'.
Re: Writing to file and reading from same file
by jmcnamara (Monsignor) on Feb 27, 2002 at 12:01 UTC

    Here is one way to do it. Have a look at perlopentut as well.
    #!/usr/bin/perl -w use strict; # Open file for reading and writing (and maybe arithmetic) open MYFILE, "+>somefile.txt" or die "Error message here: $!\n"; # Write to the file print MYFILE "These are the days\n"; print MYFILE "and these are the days\n"; # Rewind the file for reading seek(MYFILE, 0, 0); while (<MYFILE>) { print $_; } close MYFILE;

    --
    John.

Re: Writing to file and reading from same file
by projekt21 (Friar) on Feb 27, 2002 at 11:38 UTC

    Start with reading "perldoc -f open" and please show some code

    alex pleiner <alex@zeitform.de>
    zeitform Internet Dienste

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2024-04-19 10:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found