logo codesdope

Directory in Perl

Making a directory

We use mkdir to make a new directory.

mkdir(new_dir) or die "Can't create directory $_";

Deleting a directory

We use rmdir to delete or remove a directory.

rmdir(new_dir) or die "Can't create directory $_";

Knowing current working path

We can use cwd function from Cwd module to know our current working path.

use Cwd;
my $pwd = cwd();
print "$pwd\n";

Moving to different directory

We use chdir to move to a different directory which exists in the current directory.

chdir("/dir_name") or die "Can't create directory $_";

To get all files in a directory

We use readdir and closedir to open and close a directory respectively.

use Cwd;
my $pwd = cwd();

opendir my $dir, "$pwd" or die "Cannot open directory: $!";
my @files = readdir $dir;
foreach $i (@files){
  print "$i\n";
closedir $dir;

To get all files with .pl and .pm extensions

We can use grep function to get all the files with .pl and .pm extensions but a simpler way is to use glob function.

$pm = "*.pl *.pm";
my @files = glob($pm);
foreach $i (@files){
  print "$i\n";
Download Our App.
BlogsDope App
Get it on Google Play
Doubt? Ask question

Welcome.please sign up.


Welcome.please login.