|
Quick Navigation Bar regular expressions :: files and directories :: process management [ toc | forums ] |
Note: If the document URL does not begin with http://randu.org/tutorials/perl/ then you are viewing a copy. Please direct your browser to the correct location for the most recent version. |
chdir command:
chdir("/some/path") || die "Cannot chdir to /some/path ($!)";
@a = </some/path/*.c>
@a = glob("/some/path/*.c");
This would create a list of all of the .c files in the /some/path
directory. We could loop through a glob directly by:
if (-d "/some/path") {
$where = "/some/path";
} else {
$where = "/another/path";
}
while (defined($next = <$where/*.c>)) {
print "found a c file in $where directory named $name\n";
}
Notice we used the -d check for a directory for its
existence. Very powerful indeed.
opendir(DIRHANDLE, "/some/path") || die "Cannot opendir /some/path: $!";
foreach $name (sort readdir(DIRHANDLE)) {
print "found file: $name\n";
}
closedir(DIRHANDLE);
This prints out a sorted directory listing. For an unsorted list, we
could have simplified the loop construct:
while ($name = readdir(DIRHANDLE)) {
print "found file: $name\n";
}
Remember to close your directory handles!
mkdir("newdir", 0755) || die "Cannot mkdir newdir: $!";
rmdir("olddir") || dir "Cannot rmdir olddir: $!";
Notice the 0755 in the mkdir function call is permission bits. A quick
rundown: 4 = read, 5 = read + execute, 6 = read + write, 7 = read +
write + execute. You need to set the execute bit on in order
for you to access the directory.unlink function:
print "file to delete? "; chomp($name = <STDIN>); unlink($name) || die "Cannont unlink $name: $!";You can even give unlink a glob or a list of files to delete.
rename("oldfilename.txt", "newfilename.txt") || die "Cannot rename file.txt: $!";
rename("data.in", "/some/new/path/data.in") || die "Cannot rename data.in: $!";
Notice that Perl's rename function is almost the same as the
mv command under *NIX.
symlink
function:
# Under *NIX shell:
ln -s file.txt /some/other/path/reference.txt
# Under Perl:
symlink("file.txt", "/some/other/path/reference.txt") || die "Cannot symlink file.txt: $!";
Perl gives us a way to read symlinks:
if (defined($x = readlink("reference.txt"))) {
print "reference.txt points at '$x'\n";
}
chmod(0644, "file1", "file2") || die "Cannot chmod file1, file2: $!";Notice we can give a list of files to the chmod command (as we have seen with other File/Dir modification functions.
