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
EXPRis the directory path as a string (scalar, usually with a$sigil).MODEis 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:
mkdirreturns 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’smake_path(Perl 5.10+), butmkdiris 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.
mkdirwon’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’smake_pathfor 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
(empty)(empty)Was this helpful?
Related Questions
- How to use File::Find to recursively search directories in Perl?
- How to use Path::Tiny for file operations in Perl?
- How to use File::Copy to copy files in Perl?
- How to get file modification time in Perl?
- How to use File::Slurp to read files in Perl?
- How to open a file with specific encoding in Perl?