in reply to File opening/creating

You said you want to open a file for reading, but if it doesn't exist already, create it and then open it for reading. This ought to do that.

my $filename = "testfile.txt"; { open FH, "<$filename" or ( open FH, ">$filename" and close FH and redo ) or die "Bleah!\n$!"; }

There's more than one way to do it. ;)


Dave

Replies are listed 'Best First'.
Re: File opening/creating
by Abigail-II (Bishop) on Mar 03, 2004 at 22:34 UTC
    Yeah, but if the file you want to open has permission 0200, it's going to bite you twice. First it'll wipe out the data in the file, then it gets stuck in an infinite loop.

    Just use sysopen.

    Abigail

      Oh, that's a great point. The basic problem is that if the file does exist but cannot be opened for reading, yet can be opened for output, my method will clobber what's there and then continue looping forever.

      I suppose that's why I should have just used the '-e' function:

      if ( -e $filename ) { open FH, "<$filename" or die $!; } else { open FH, ">$filename" or die $!; close FH; open FH, "<$filename" or die $!; }

      At least this eliminates the potential for the endless loop.


      Dave

        The potential problem here is that you might wipe out data created by another process. Testing for existance and the following open aren't atomic, and a lot of things can happen in between.

        Really, do use sysopen. That's atomic.

        Abigail

Re: Re: File opening/creating
by kokoko12000 (Novice) on Mar 03, 2004 at 22:35 UTC
    Thanks for your replies. thats lot of info.