How to create a directory with the "correct" permissions using Perl mkdir?

I need help with this program. As part of my project, I need to create a directory. I used the system function for this, but it was later said that Perl has a built-in call to mkdir .

I'm on Ubuntu 10.04. The mkdir problem does not seem to work as needed.

Creates a directory, but permissions are different. Here is my function that creates the directory:

 sub createDir { my ($dir,$perm) = @_; unless(-d $dir) { mkdir $dir,$perm or die "$!"; } } 

and I call it in many parts of my program as follows:

 createDir('.today','0755'); 

the .today directory is created, but the problem is related to permissions, it does not have permission 0755 .

What am I doing wrong?

Details of my Perl:

  $ perl -v

 This is perl, v5.8.8 built for x86_64-linux-thread-multi 
+4
source share
3 answers

You pass permission as a string . mkdir expects it to be numeric . But the octal number inside the string is interpreted as decimal . Therefore, '0755' interpreted as decimal 755 and used by mkdir .

To fix this, you can call a routine that passes its numerical resolution:

 createDir('.today',0755); 

Alternatively, you can use the oct function to convert an octal string to a numeric value.

The subroutine call remains the same:

 createDir('.today','0755'); 

but its definition changes the use of the oct function as:

 mkdir $dir,oct($perm) or die "$!"; 
+9
source

The second argument to mkdir is not creation mode. This is the mask that will & ed with ~umask to determine the creation mode. If you specify 0755 and your umask is 027, then 0755 &~ 0027 == 0750 . Remember to save everything in octal, not decimal.

There are also constants for these things available through use POSIX qw[ :sys_stat_h ] , such as S_IRWXU , S_IWGRP and S_ISVTX , but this may be more of a problem than they are worth.

+3
source

After you have fixed the codeaddict string and number error and noted the tchrist umask problem, you should call chmod in the new directory after creating it if you need certain permissions.

Usually I call mkdir without a mask, and then chmod into the directory with the permissions that I want.

Check them out of the shell:

 $ perldoc -f mkdir $ perldoc -f chmod $ perldoc -f unmask 

You can also set umask to zero before calling mkdir, you will need to do it this way if you need to create a directory with the correct permissions atomically. Maybe something similar to what you are looking for:

 sub createDir { my ($dir, $perm) = @_; if(!-d $dir) { my $old = umask(0); mkdir($dir, $perm) or die "$!"; umask($old); } else { chmod($dir, $perm); } } 
+2
source

All Articles