Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 925
Haritz Avatar asked Dec 13 '12 08:12

Haritz


People also ask

How do you create a new file in Perl?

open (FH, '>', “filename. txt”); If the file is existing then it truncates the old content of file with the new content. Otherwise a new file will be created and content will be added.

How do I create a log file in Perl script?

Use Sys::Syslog to write log messages. But since you're opening a log. txt file with the handle OUTPUT , just change your two print statements to have OUTPUT as the first argument and the string as the next (without a comma). Not only because it's in your while loop.

How do I write an array to a file in Perl?

Write array to a file : file write « File « Perl Writes to the standard error file.


1 Answers

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.

like image 82
Demnogonis Avatar answered Sep 30 '22 01:09

Demnogonis