file-io beginner

How to create a directory in Perl?

Question

How to create a directory in Perl?

Creating a directory in Perl is simple using the built-in mkdir function, which creates one directory with optional permissions. It’s a core function with straightforward syntax but requires attention to argument commas and proper permission format.

Using mkdir in Perl

The correct syntax is:

mkdir EXPR, MODE
  • EXPR is the directory path as a string (scalar, usually with a $ sigil).
  • MODE is an optional octal number (e.g., 0755) defining permissions.

The square brackets seen in documentation mean optional parameters; they should never appear literally in code. Also, don’t forget the comma between arguments, or Perl will throw a syntax error.

Perl Concepts Involved

  • Sigils: Scalars such as directory names use $.
  • Context: mkdir returns true (1) if successful, false otherwise.
  • Error handling: Check mkdir’s return value; $! contains the last OS error.
  • TMTOWTDI (There’s More Than One Way To Do It): For nested directories, use File::Path’s make_path (Perl 5.10+), but mkdir is enough for a single directory.

Common Pitfalls

  • Omitting the comma between arguments causes syntax errors.
  • Not checking the return value hides failure causes like permission issues.
  • Specifying mode without a leading zero means it won’t be interpreted as octal.
  • mkdir won’t create nested directories automatically.

Runnable Perl Example

#!/usr/bin/perl
use strict;
use warnings;

my $dir = "example_dir";    # Directory to create
my $mode = 0755;            # Permissions (octal)

if (mkdir($dir, $mode)) {
    print "Directory '$dir' created successfully with mode ", sprintf("%04o", $mode), ".\n";
} else {
    warn "Failed to create directory '$dir': $!\n";
}

This script tries to create a directory named example_dir with permissions 0755. It prints a success message or an error with the system’s reason. Run it in a writable location to see it working.

Summary

  • Use mkdir($dirname, $mode) with a comma separating arguments.
  • Check the return value to handle errors properly.
  • Pass permissions as an octal number starting with zero (e.g. 0755).
  • Use File::Path’s make_path for recursive directory creation (Perl 5.10+).

Following this guidance ensures simple and reliable directory creation in Perl scripts.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 12ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
(empty)
STDERR
(empty)

Was this helpful?

Related Questions