- mkdir "test", 0755 or warn"$!";
use the oct function, which forces octal interpretation
of a string whether or not there’s a leading zero:
mkdir $name, oct($permissions);
The need for the extra oct function shows up most
often when the value comes from user input. For example, suppose we take the argu-
ments from the command line:
- my ($name, $perm) = @ARGV; # first two args are name, permissions
-
mkdir $name, oct($perm) or die "cannot create $name: $!";
To remove
empty directories, use the rmdir function in a manner similar to the
unlink function, although it can only remove on directory per call:
- foreach my $dir (qw(fred barney betty)) {
-
rmdir $dir or warn "cannot rmdir $dir: $!\n";
-
}
The rmdir operator fails for nonempty directories. As a first pass, you can attempt to
delete the contents of the directory with unlink, then try to remove what should now
be an empty directory.
- my $temp_dir = "/tmp/scratch_$$"; # based on process ID; see the text
-
mkdir $temp_dir, 0700 or die "cannot create $temp_dir: $!";
-
...
-
# use $temp_dir as location of all temporary files
-
...
-
unlink glob "$temp_dir/* $temp_dir/.*"; # delete contents of $temp_dir
-
rmdir $temp_dir; # delete now-empty directory
For a more robust solution, check out the rmtree function
provided by the File::Path module of the standard distribution.
chmod 0755, "fred", "barney";
As with many of the operating system interface functions, chmod returns the number of
items successfully altered, and when used with a single argument, sets $! in a sensible
way for error messages when it fails.
If the operating system permits it, you may change the ownership and group member-
ship of a list of files (or filehandles) with the chown function. The user and group are
both changed at once, and both have to be the numeric user-ID and group-ID values.
For example:
my $user = 1004;
my $group = 100;
chown $user, $group, glob "*.o";
What if you have a username like merlyn instead of the number? Simple. Just call the
getpwnam function to translate the name into a number, and the corresponding
getgrnam† to translate the group name into its number:
- defined(my $user = getpwnam "merlyn") or die "bad user";
-
defined(my $group = getgrnam "users") or die "bad group";
-
chown $user, $group, glob "/home/merlyn/*";
The defined function verifies that the return value is not undef, which will be returned
if the requested user or group is not valid.
The chown function returns the number of files affected, and it sets $! on error.
阅读(664) | 评论(0) | 转发(0) |