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 (Saint) 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;