Perl Mkdir — How To Create Directories in Perl

mkdir() allows you to create directories in your Perl script. The following program creates a directory called “temp”.

use strict;
use warnings;

sub main {
	my $directory = "temp";
	
	unless(mkdir $directory) {
		die "Unable to create $directory\n";
	}
}

main();

Note that we’ve caught errors by checking the return value; mkdir() returns true if it succeeds, and false if it fails.

The second time we run this script, we get:

Unable to create temp

… since the directory now already exists.

Learn Perl By Doing It

box3d_160x120

Get the complete course here

Includes 11 completely free videos – no subscription necessary.

Of course you can test to see if the directory already exists before trying to create it using -e. The following program will only try to create a directory if it doesn’t already exist; if the directory does not exist, the program tries to create it; if creation fails, a fatal error warning is issued.

use strict;
use warnings;

sub main {
	my $directory = "temp";
	
	unless(-e $directory or mkdir $directory) {
		die "Unable to create $directory\n";
	}
}

main();

For UNIX-like systems, you can also specify permissions to mkdir(); the directory will then be created with the permissions you specify (although sometimes I’ve had problems getting this to work for full 777 permissions — maybe it depends on your precise UNIX set up).

This program create a directory called “fruit” with permissions set to 0755 (only the owner has the permission to write to the directory; group members and others can only view files and list the directory contents).

use strict;
use warnings;

sub main {
	my $directory = "fruit";

	unless(mkdir($directory, 0755)) {
		die "Unable to create $directory\n";
	}
}

main();

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Posted in Perl |