bob*_*bah 25
码:
chdir('path/to/dir') or die "$!";
Run Code Online (Sandbox Code Playgroud)
的Perldoc:
chdir EXPR
chdir FILEHANDLE
chdir DIRHANDLE
chdir Changes the working directory to EXPR, if possible. If EXPR is omitted,
changes to the directory specified by $ENV{HOME}, if set; if not, changes to
the directory specified by $ENV{LOGDIR}. (Under VMS, the variable
$ENV{SYS$LOGIN} is also checked, and used if it is set.) If neither is set,
"chdir" does nothing. It returns true upon success, false otherwise. See the
example under "die".
On systems that support fchdir, you might pass a file handle or directory
handle as argument. On systems that don't support fchdir, passing handles
produces a fatal error at run time.
Run Code Online (Sandbox Code Playgroud)
Ped*_*erg 14
你不能通过调用来做这些事情的原因system是,system它将启动一个新进程,执行你的命令,并返回退出状态.因此,当您调用时,system "cd foo"您将启动一个shell进程,该进程将切换到"foo"目录然后退出.在perl脚本中不会发生任何后果.同样,system "exit"将启动一个新进程并立即再次退出.
对于cd案例你想要的是 - 正如bobah指出的那样 - 函数chdir.退出程序时,有一个功能exit.
但是 - 这些都不会影响您所在的终端会话的状态.在您的perl脚本完成后,终端的工作目录将与您开始之前的工作目录相同,并且您将无法通过以下方式退出终端会话调用exit你的perl脚本.
这是因为你的perl脚本再次是一个与你的终端shell不同的进程,并且在不同进程中发生的事情通常不会相互干扰.这是一个功能,而不是一个bug.
如果您希望在shell环境中更改内容,则必须发出shell理解和解释的指令. cd是shell中的内置命令,就是这样exit.
我总是喜欢提到File::chdir-ing cd。它允许更改封闭块本地的工作目录。
正如 Peder 提到的,您的脚本基本上是与 Perl 绑定在一起的所有系统调用。我提出了一个更加 Perl 的实现。
"wget download.com/download.zip";
system "unzip download.zip"
chdir('download') or die "$!";
system "sh install.sh";
Run Code Online (Sandbox Code Playgroud)
变成:
#!/usr/bin/env perl
use strict;
use warnings;
use LWP::Simple; #provides getstore
use File::chdir; #provides $CWD variable for manipulating working directory
use Archive::Extract;
#download
my $rc = getstore('download.com/download.zip', 'download.zip');
die "Download error $rc" if ( is_error($rc) );
#create archive object and extract it
my $archive = Archive::Extract->new( archive => 'download.zip' );
$archive->extract() or die "Cannot extract file";
{
#chdir into download directory
#this action is local to the block (i.e. {})
local $CWD = 'download';
system "sh install.sh";
die "Install error $!" if ($?);
}
#back to original working directory here
Run Code Online (Sandbox Code Playgroud)
它使用两个非核心模块(并且Archive::Extract从 Perl v5.9.5 开始才成为核心模块),因此您可能必须安装它们。使用该cpan实用程序(或ppm在 AS-Perl 上)来执行此操作。