Regex 关于perl中的chdir,如何返回到上一个目录

Regex 关于perl中的chdir,如何返回到上一个目录,regex,perl,Regex,Perl,指令1:a/b/c/d 指令2:e/f/g/h 现在,我在DIR1中执行一个Perl脚本,并从chdir到DIR2(使用DIR2中的数据),在执行该脚本后,我想返回DIR1。是否为默认值,如果不是,则应使用什么命令 提前感谢。您应该在第一次使用chdir之前使用 use Cwd; # get and save current working directory my $dir = getcwd; chdir("/some/path"); # do stuff # now get back

指令1:a/b/c/d 指令2:e/f/g/h

现在,我在DIR1中执行一个Perl脚本,并从chdir到DIR2(使用DIR2中的数据),在执行该脚本后,我想返回DIR1。是否为默认值,如果不是,则应使用什么命令

提前感谢。

您应该在第一次使用chdir之前使用

use Cwd;

# get and save current working directory
my $dir = getcwd;

chdir("/some/path");
# do stuff

# now get back to original dir
chdir($dir);

你的问题不是很清楚。我想你可能会问两件不同的事情。如果我了解您的设置,请执行以下操作:

$ cd a/b/c/d
$ perl stuff.pl
stuff.pl
chdir(“e/f/g/h”)
。现在您要返回到
a/b/c/d
。对吗

案例1: 您希望在脚本完成后返回。由于脚本是在子流程中执行的,因此当您退出子流程时,您将回到启动脚本之前的位置。没有什么特别需要做的

案例2: 您希望在脚本完成之前返回。在这种情况下,您可以记住当前目录:

#!/usr/bin/env perl

# remember the directory
my $curdir = `pwd`;
chdir("e/f/g/h");
# ...
# return back:
chdir($curdir);
# ...

那些反对票是怎么回事?踩到别人的鞋子?答案在我看来并不低落…@DeVadder:不知道。我能想到的唯一一件事是,微软的人不赞成使用更便携的
pwd
,而不赞成使用更便携的
getcwd()
。如果有很好的方法在Perl中获取信息,你不应该使用其他程序。它就像
使用Cwd一样简单;my$curdir=cwd。应该注意的是,Perl附带了一个。如果你能很容易地使你的代码平台独立,你应该这样做。@BradGilbert:是的。考虑到要改变它,我觉得从chrsblck的代码中剥离是不对的,所以我就保持原样了。
    As per i get your question your purpose is first go to some directory like /a/b/c then  execute some stuff as per requirement then next step is go to another directory like  /e/f/g & execute some stuff.so i write below code as per your need.      

            $dir1 = "/home";
    # This changes perl directory  and moves you inside /home directory.
    chdir( $dir1 ) or die "Couldn't go inside $dir directory, $!";
    print "Your first  location is $dir1\n";
            #Execute your stuff in dir1 
    $dir2 = "/home/prasad";
    # This changes perl directory  and moves you inside /home directory.
    chdir( $dir2 ) or die "Couldn't go inside $dir directory, $!";
    print "Your second  location is $dir2\n";
            #Execute your stuff in dir2