5

我想使用 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
}

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

例如。

.../Scripts/ScriptContainFolder> perl FolderCreator.pl New
.../Scripts> perl ./ScriptContainFolder/FolderCreator.pl New

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

4

3 回答 3

8

您可以使用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";
于 2011-05-11T06:25:08.303 回答
4

我认为它的工作原理与它所写的完全一样,除了你有一个错字,即缺少一个右括号chdir

unless(chdir($ARGV[0])) {   #fixed typo
    mkdir($ARGV[0], 0700);
    chdir($ARGV[0]) or die "can't chdir $ARGV[0]\n";
}

脚本运行如下:

  1. 如果脚本不能 chdir 到 $ARGV[0] 那么:
  2. 使用权限掩码 0700 创建目录 $ARGV[0]。
  3. 将工作目录更改为 $ARGV[0] 或退出脚本并显示错误文本“cant chdir..”。

脚本的起始目录将是调用它的目录,无论该目录是什么。在 *nix 上,这将是$ENV{PWD}脚本中的变量。它将在它有权这样做的任何文件夹中创建一个新文件夹。

我认为这种行为是合乎逻辑的,而且应该如此。如果您希望您的示例正常工作,请执行以下操作:

.../Scripts> perl ./ScriptContainFolder/FolderCreator.pl ScriptContainFolder/New

也可以使用绝对路径,比如

?> FolderCreator.pl /home/m/me/Scripts/ScriptContainFolder/New

ETA:哦,你当然应该总是把它放在你的脚本中,不管它有多小:

use strict;
use warnings;
于 2011-05-11T06:41:57.230 回答
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;
于 2011-05-12T10:42:05.253 回答