Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

my $FILE;

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

close($FILE);

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top