PERL脚本:mkdir和chdir的问题

时间:2017-04-07 10:20:45

标签: perl perl-module file-copying

checkAndCreateDirectory();
moveFiles();
sub checkAndCreateDirectory {
    my $dirname = "launchpad/config/com/adobe/granite/auth/saml/SamlAuthenticationHandler";
    my @folders = split /\/|\\/, $dirname;
    map { mkdir $_; chdir $_; } @folders;
}
sub moveFiles {
    my $source_dir = "SamlAuthenticationHandler";
    my $destination_dir = "launchpad/config/com/adobe/granite/auth/saml/SamlAuthenticationHandler";
    opendir(my $DIR, $destination_dir) || die "can't opendir $source_dir: $!";
    move("$source_dir", "$destination_dir") or die "FAIL : Unable to add config -> $!";
}

checkAndCreateDirectory() moveFiles()子例程正在使用单独的脚本正常运行但是当尝试在同一脚本中运行时会抛出错误:没有此类文件或目录

任何人都可以帮我解决这个问题吗?

有什么问题吗?
  

map {mkdir $ ; chdir $ ; } @folders;

1 个答案:

答案 0 :(得分:3)

问题是,您chdir进入了checkAndCreateDirectory的所有子目录,但从未返回到您开始的位置,因此当您致电moveFiles时,您处于错误的位置且不能找到你的$destination_dir

我会像这样简化你的脚本:

use warnings;
use strict;

use File::Copy::Recursive qw( dirmove );
use File::Path qw( make_path );

my $saml_handler_path = 'launchpad/config/com/adobe/granite/auth/saml/SamlAuthenticationHandler';

make_path $saml_handler_path
    or die "Unable to create path '$saml_handler_path' : $!";

my $source_dir = "SamlAuthenticationHandler";
my $dest_dir = $saml_handler_path;

dirmove( $source_dir, $dest_dir )
    or die "Unable to move $source_dir to $dest_dir : $!";