perl function chmod
In Perl, the chmod
function is used to change the permissions of a file or directory. It takes two arguments: the new mode as an integer and the list of files to modify. The mode is a combination of permissions specified in octal form.
Here's an example that demonstrates the use of the chmod
function:
use strict; use warnings; # create a test file my $filename = 'test.txt'; open(my $fh, '>', $filename) or die "Cannot open file: $!"; close($fh); # set the file permissions to 0644 (rw-r--r--) chmod(0644, $filename); # get the current file permissions my $mode = (stat($filename))[2] & 07777; printf "Current file mode: %04o\n", $mode; # set the file permissions to 0755 (rwxr-xr-x) chmod(0755, $filename); # get the updated file permissions $mode = (stat($filename))[2] & 07777; printf "Updated file mode: %04o\n", $mode; # remove the test file unlink $filename;Soucre:www.theitroad.com
In the above example, we first create a test file using the open
function and then close it. We then use the chmod
function to set the file permissions to 0644
(readable and writable by the owner, readable by everyone else). We use the stat
function to get the current file permissions, which we print to the screen using the printf
function.
We then use the chmod
function again to set the file permissions to 0755
(readable, writable, and executable by the owner, readable and executable by everyone else). We again use the stat
function to get the updated file permissions, which we print to the screen using the printf
function.
Finally, we remove the test file using the unlink
function.
When run, the above example will output something like the following:
Current file mode: 0644 Updated file mode: 0755
This indicates that the file permissions were successfully changed from 0644
to 0755
.