Copy chmod permissions from one file to another

This script demonstrates how to copy the permissions of one file to another file so that they both have the same permissions. For example, if the first file is read-only, then the second file will be made read-only too.

use warnings;
use strict;
use utf8;
use File::Slurper qw/read_binary write_binary/;
my $filea = "$0";
my $text = read_binary ($filea);
my $fileb = "$filea-copy";
if (-f $fileb) {
    unlink $fileb or die $!;
write_binary ($fileb, $text);
my $permissionsa = (stat ($filea))[2];
my $permissionsb = (stat ($fileb))[2];
printf ("A: %s - %o\n", $filea, $permissionsa);
printf ("B before: %s - %o\n", $fileb, $permissionsb);
chmod $permissionsa, $fileb or die $!;
$permissionsb = (stat ($fileb))[2];
printf ("B after: %s - %o\n", $fileb, $permissionsb);


The program's output looks like this:

$ perl 
A: - 100755
B before: - 100644
B after: - 100755

Web links

Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock ( or use the discussion group at Google Groups. / Privacy / Disclaimer