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

Hi all, Sorry for this newbie question. I want to open a file, and if the file is not present in the path, I want to create it automatically instead of displaying an error. I can do open(TESTFILE, ">$groups_file"). This creates the file if it is not present. This is for output into the file. But I am opening the file to read and not to write into it. Pls give me any suggestions. -Vid.

Replies are listed 'Best First'.
Re: File opening/creating
by Abigail-II (Bishop) on Mar 03, 2004 at 22:27 UTC
    use Fcntl; sysopen my $fh => "/path/to/file", O_RDONLY | O_CREAT, 0666 or die;

    Abigail

Re: File opening/creating
by davido (Cardinal) on Mar 03, 2004 at 22:27 UTC
    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

      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

      Thanks for your replies. thats lot of info.