Chown function in Perl


I have problems with the working of the chown function in Perl. I have a script:


$file   = "";
$file   = $ARGV[0];

$user   = "jboss";
$group  = "jboss";

if ($file eq "")
    print "Syntax: $0 <file>\n";
    exit 0;

@file = ($file);

print "Chowning the file $file to $user:$group\n";

$number = chown $user, $group, "$file";

print "Number of ownerships changed: $number\n";

exit 0;

SELinux is enabled and permissive, but:

root# ls -l file 
-rw-r--r--. 1 root root 0 Jul 26 10:27 file  
root# id -a jboss uid=666(jboss) gid=666(jboss) groups=666(jboss)  
root# file   
Chowning the file file to jboss:jboss  
Number of ownerships changed: 1  
root# ls -l file 
-rw-r--r--. 1 root root 0 Jul 26 10:27 file

Question: what do I miss here ? Of course you can write a qx("/usr/bin/chown jboss:jboss ") here, but the whole point here is to use a more platform independent function here, and not a backtick quote

Best Answer

Perl's chown function expects a numeric uid/gid instead of a user/group name. See perldoc -f chown.

To get the uid from the user name and the gid from the group name, you can use the getpwnam and getgrnam functions like this:

my $uid = getpwnam $user_name;
my $gid = getgrnam $group_name;
chown $uid, $gid, $file_name;
Related Question