Perl Directories

Following are the standard functions used to play with directories.

1) Display all the Files
There are various ways to list down all the files available in a particular directory. 
a. Using the glob operator.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#!/usr/bin/perl

# Display all the files in a directory.
$dir = "C:/temp";
my @files = glob "$dir/*.*";

foreach (@files ) {
   print $_ . "\n";
}

# Display all the text files in a directory.
print "\n Display all the text files in a directory\n";
my @files = glob "$dir/*.txt";

foreach (@files ) {
   print $_ . "\n";
}

b. Open a directory and list out all the files available inside the directory.
1
2
3
4
5
6
7
#!/usr/bin/perl

opendir (DIR, "C:/temp") or die "Couldn't open directory, $!";
while ($file = readdir DIR) {
   print "$file\n";
}
closedir DIR;

2) Create new Directory
1
2
3
4
5
6
#!/usr/bin/perl

$dir = "C:/temp1";

# This creates perl directory in /tmp directory.
mkdir( $dir ) or die "Couldn't create $dir directory, $!";

3) Remove a directory
1
2
3
4
5
6
#!/usr/bin/perl

$dir = "C:/temp1";

# This removes perl directory from /tmp directory.
rmdir( $dir ) or die "Couldn't remove $dir directory, $!";


<-- Previous || Next -->

1 comment: