Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Safe File Handling

by CloneArmyCommander (Friar)
on Nov 06, 2005 at 01:02 UTC ( [id://506051]=perlquestion: print w/replies, xml ) Need Help??

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

Problem

I just accidently clobbered a file I worked hours to code (luckily I have two backups, one on my computer and another on a web server, and a hard copy).

Question

When creating a file through perl, is there a way to check if a file by that name already exists, and complain if it does exist.

I have an idea, but I am looking for a quick solution. I think I could pack some code in that opens the current directory, and tests the given name against all of the files in the directory.

Is there a quicker fix than me having to kluge that in.

2005-11-06 Retitled by planetscape, as per Monastery guidelines
Original title: 'Safe File Hadling'

Replies are listed 'Best First'.
Re: Safe File Handling
by tinita (Parson) on Nov 06, 2005 at 01:14 UTC
      Thanks :D!
Re: Safe File Handling
by gloryhack (Deacon) on Nov 06, 2005 at 01:18 UTC
    See perldoc perlopentut, where in addition to many useful nuggets, you'll find this one:
    sysopen(FH, $path, O_WRONLY | O_EXCL | O_CREAT);
      Thank you :D!
Re: Safe File Handling
by EvanCarroll (Chaplain) on Nov 06, 2005 at 02:30 UTC
    You might also want to check out the -i flag on perl. While I know you said 'creating a file through perl' it would seem that -i might be worth knowing.
    -i[extension] edit <> files in place (makes backup if extension supp +lied)


    Evan Carroll
    www.EvanCarroll.com
Re: Safe File Handling
by vek (Prior) on Nov 06, 2005 at 07:26 UTC

    The -e filetest will give you what you need.

    my $filename = 'somefilename'; if (-e $filename) { print "File $filename already exists.\n"; } else { # create the file here... }

    -- vek --
Re: Safe File Handling
by Anonymous Monk on Nov 06, 2005 at 18:36 UTC
    once you are set to the right path there are a variety of file tests available, one of which is -e to test if it exists. Usage could look like: die "Don't overwrite a file that already exists\n" if -e $filename; Being new to this myself I had to open up the llama book for reference (its chapter 11, page 155 of the 4th edition) or hidden in chapter 3 of the cammel.

Log In?
Username:
Password:

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

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

    No recent polls found