使用perl创建文件夹

Dar*_*Ray 5 perl mkdir

我想使用perl创建文件夹,在同一文件夹中,存在perl脚本.我创建了FolderCreator.pl,它需要输入参数folder name.

unless(chdir($ARGV[0]){ # If the dir available change current , unless
    mkdir($ARGV[0], 0700);                             # Create a directory
    chdir($ARGV[0]) or die "can't chdir $ARGV[0]\n";    # Then change or stop
}
Run Code Online (Sandbox Code Playgroud)

只有当我们在它所在的同一文件夹中调用scipt时,这才能正常工作.如果在另一个文件夹中调用它,如果不起作用.

例如.

.../Scripts/ScriptContainFolder> perl FolderCreator.pl New
.../Scripts> perl ./ScriptContainFolder/FolderCreator.pl New
Run Code Online (Sandbox Code Playgroud)

第一个工作正常但第二个工作没有.有没有办法创建这些文件夹?

Mig*_*Prz 7

你可以使用FindBin模块,它给我们$ Bin变量.它找到脚本bin目录的完整路径,以允许使用相对于bin目录的路径.

use FindBin qw($Bin);

my $folder = "$Bin/$ARGV[0]";

mkdir($folder, 0700) unless(-d $folder );
chdir($folder) or die "can't chdir $folder\n";
Run Code Online (Sandbox Code Playgroud)


Dar*_*Ray 1

我已经完成了工作,这是代码...谢谢大家的帮助...

#!usr/bin/perl

###########################################################################################
# Needed variables
use File::Path;
use Cwd 'abs_path';
my $folName     = $ARGV[0];
#############################################################################################
# Flow Sequence 
if(length($folName) > 0){
    # changing current directory to the script resides dir
    $path = abs_path($0);
    $path = substr($path, 0, index($path,'FolderCreator.pl') );
    $pwd = `pwd`;
    chop($pwd);
    $index = index($path,$pwd);
    if( index($path,$pwd) == 0 ) {
        $length = length($pwd);
        $path = substr($path, $length+1);

        $index = index($path,'/');
        while( $index != -1){
            $nxtfol = substr($path, 0, $index);
            chdir($nxtfol) or die "Unable to change dir : $nxtfol"; 
            $path = substr($path, $index+1);
            $index = index($path,'/');
        } 
    }
    # dir changing done...

    # creation of dir starts here
    unless(chdir($folName)){        # If the dir available change current , unless
        mkdir("$USER_ID", 0700);    # Create a directory
        chdir($folName) or $succode = 3;    # Then change or stop
    }
}
else {
    print "Usage : <FOLDER_NAME>\n";    
}
exit 0;
Run Code Online (Sandbox Code Playgroud)