Create a file in a directory using Perl

Haritz picture Haritz · Dec 13, 2012 · Viewed 32.8k times · Source

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.

Answer

Demnogonis picture Demnogonis · Dec 13, 2012
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.