Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

open file, write then read problem

by doniking (Novice)
on Jun 15, 2009 at 00:18 UTC ( #771493=perlquestion: print w/replies, xml ) Need Help??

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

hello, i have this code,
my $file1_temp = "output.txt"; open (FILE1_TEMP, "+>$file1_temp") or die "Could not open $file1_temp: + $!"; print FILE1_TEMP "hello, world!"; while (<FILE1_TEMP>) { print $_; } close FILE1_TEMP;
but it prints nothing to the screen. Could somebody give an advice?

Thanks so much!
Donie

Replies are listed 'Best First'.
Re: open file, write then read problem
by GrandFather (Sage) on Jun 15, 2009 at 00:35 UTC

    We are good at giving advice. ;)

    First, always use strictures (quite likely you are in fact, but didn't include them in your sample).

    Use the three parameter version of open and use lexical file handles:

    open my $FILE1_TEMP, '+>', $file1_temp or die "Could not open $file1_t +emp: $!";

    However, that is probably not the advice you want. Your code appends a string to a file then prints everything from the end of the file to, well, the end of the file - that is, nothing (as you have noticed).

    The fix is either to close and reopen the file, or to seek to the start before your while loop:

    use strict; use warnings; my $file1_temp = "delme.txt"; open my $ioFile, '+>', $file1_temp or die "Could not open $file1_temp: + $!"; print $ioFile "hello, world!"; seek $ioFile, 0, 0; print while <$ioFile>; close $ioFile;

    True laziness is hard work
      it works
      my ebook didn't explain about this pointer.

      Thanks, all. you save me.

      i'll be back

Re: open file, write then read problem
by Anonymous Monk on Jun 15, 2009 at 00:41 UTC
    open the file handler for reading the file after u close the fh for writing. In your script the file pointer is pointing to new line hence is not printing any data open (FILE1_TEMP, "+>$file1_temp") or die "Could not open $file1_temp: $!"; print FILE1_TEMP "hello, world!"; close FILE1_TEMP; open (READFILE1_TEMP, "$file1_temp") or die "Could not open $file1_temp: $!"; while (<READFILE1_TEMP>) { print $_; } close READFILE1_TEMP;

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (3)
As of 2020-02-24 09:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What numbers are you going to focus on primarily in 2020?










    Results (104 votes). Check out past polls.

    Notices?