msikd65
msikd65

Reputation: 437

How do I create a directory in Perl?

I am new to Perl and trying to write text files. I can write text files to an existing directory no problem, but ultimately I would like to be able to create my own directories.

I am going to download files from my course works website and I want to put the files in a folder named after the course. I don't want to make a folder for each course manually beforehand, and I would also like to eventually share the script with others, so I need a way to make the directories and name them based on the course names from the HTML.

So far, I have been able to get this to work:

use strict;
my $content = "Hello world";
open MYFILE, ">C:/PerlFiles/test.txt";
print MYFILE $content;
close (MYFILE);

test.txt doesn't exist, but C:/PerlFiles/ does and supposedly typing > allows me to create files, great.

The following, however does not work:

use strict;
my $content = "area = pi*r^2";
open MYFILE, ">C:/PerlFiles/math_class/circle.txt";
print MYFILE $content;
close (MYFILE);

The directory C:/PerlFiles/math_class/ does not exist.

I also tried sysopen but I get an error when adding the flags:

use strict;
my $content = "area = pi*r^2";
sysopen (MYFILE, ">C:/PerlFiles/math_class/circle.txt", O_CREAT);
print MYFILE $content;
close (MYFILE);

I got this idea from the Perl Cookbook chapter 7.1. Opening a File. It doesn't work, and I get the error message Bareword "O_CREAT" not allowed while "strict subs" in use. Then again the book is from 1998, so perhaps O_CREAT is obsolete. At some point I think I will need to fork over the dough for an up-to-date version.

But still, what am I missing here? Or do the directories have to be created manually before creating a file in it?

Upvotes: 3

Views: 3789

Answers (2)

Dallaylaen
Dallaylaen

Reputation: 5318

Use File::Path to create arbitrarily deep paths. Use dirname to find out a file's containing directory.

Also, use lexical file handles and three-argument open:

open(my $fd, ">", $name) or die "Can't open $name: $!";

Upvotes: 7

berekuk
berekuk

Reputation: 186

Right, directories have to be created manually. Use mkdir function.

You can check if directory already exists with -d $dir (see perldoc -f -X).

Upvotes: 8

Related Questions