dark

Changing file permissions in Perl

blank

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):

    my @fstats = stat($file);
    my $fperms = sprintf('%04o', ($fstats[2] & 07777) & ~(00222) );
    chmod oct($fperms), $file;

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

    my @fstats = stat($file);
    my $fperms = sprintf('%04o', ($fstats[2] & 07777) & 00222 );
    chmod oct($fperms), $file;

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

    my @fstats = stat($file);
    my $fperms = sprintf('%04o', ($fstats[2] & 07777) & 00644 );
    chmod oct($fperms), $file;
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.

Previous Post

Secure MySQL Backups with GnuPG

Next Post

Check if a NFS share is mounted

Related Posts