Changing file permissions in Perl

There are definetly a few modules on CPAN which will allow to easily change file permissions in Perl, but you do not always have the chance or possibility to install CPAN modules.
The following examples explain how to change the original file permissions to either remove or set new permissions.

One way of doing this, is by getting the filesystem statistics with stat and creating a bunch of if-statements where you check every possibility. This of course creates bad code and doesn’t the laziness of a true Perl programmer.

Another way, and a much more elegant way, is by using bit operators and not checking what the current permissions are, you just remove or add what is required.

For example, remove all write permissions (for user, groups and others):

And now put them back again (for user, groups and others):

The important part in the above examples is:

  • & ~(00222)
  • & 00222

These masks define the new permissions bits that either need to be removed or set.

Last example: making sure the file’s permissions are 644


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.