perlcreatefile

Create a file in a directory using Perl


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.


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.