in reply to Check if a file exists and if not create it

Is there a reason to use IO::File instead of open $fh,'>>',$filename;?

use strict; sub test { my $filename = 'test2.txt'; if (-f $filename) { print "File Exists!"; } else { print "File does not exist"; } } sub openFile { open my $fh, '>>', 'test2.txt'; print "file open!\n"; print $fh "The stuff I wanted to add to the end of the file.\n"; } test(); openFile(); test();

Output:

$: perl foo.pl File does not exist file open File Exists! $: cat test2.txt The stuff I wanted to add to the end of the file. $: perl foo.pl File Exists! file open File Exists! $: cat test2.txt The stuff I wanted to add to the end of the file. The stuff I wanted to add to the end of the file. $:
1 Peter 4:10

Replies are listed 'Best First'.
Re^2: Check if a file exists and if not create it
by Wroof (Novice) on Aug 20, 2014 at 21:26 UTC
    hey thanks for this. there was no reason I was using IO:File apart from what I found online in a tutorial. I found the problem was with where the program was creating the file 'C:\Users\user' instead of that I expected it to create it in the same directory the program is in.