5

How can I create a new file, in which I intend to write in a existing directory using open() in Perl?

I tried like this:

my $existingdir = './mydirectory';

open my $fileHandle, ">>", "$existingdir/filetocreate.txt" or die "Can't open '$existingdir/filetocreate.txt'\n";

But it won't work.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Haritz
  • 1,702
  • 7
  • 31
  • 50
  • 4
    Instead of "Can't open ..." say "Can't open ...: $!" to know the exact reason for error. Either ./mydirectory doesn't exist or you don't have write perms. – Himanshu Dec 13 '12 at 08:51
  • 1
    That works fine if `mydirectory` exists in the current working directory and you have permission to create in it. – ikegami Dec 13 '12 at 08:54
  • 1
    Yes, this code works fine for me. Another thing to check: are you sure that Perl's current working directory is what you think it is? Check with CWD: http://perldoc.perl.org/Cwd.html – dan1111 Dec 13 '12 at 08:54

2 Answers2

13
my $existingdir = './mydirectory';
mkdir $existingdir unless -d $existingdir; # Check if dir exists. If not create it.
open my $fileHandle, ">>", "$existingdir/filetocreate.txt" or die "Can't open '$existingdir/filetocreate.txt'\n";
print $fileHandle "FooBar!\n";
close $fileHandle;

This should work for you.

Demnogonis
  • 3,172
  • 5
  • 31
  • 45
  • -1 the OP wants to create a file "in an existing directory". This might make the script run without dying, but it doesn't diagnose and solve the actual problem. – dan1111 Dec 13 '12 at 09:04
  • 2
    Well, I see the answer was accepted. While I think my point stands, I will remove my downvote, since you successfully read the OP's mind about what the real problem was! – dan1111 Dec 13 '12 at 09:06
  • 2
    Would be better to use File::Path's `mkpath` than `mkdir` – ikegami Dec 13 '12 at 09:10
1
my $FILE;

open($FILE, ">>File.txt")||die("Cannot open file:".$!);

close($FILE);

You may append directory location in place of File.txt.

serenesat
  • 4,611
  • 10
  • 37
  • 53
KSRKSR
  • 129
  • 1
  • 5