我在尝试以下操作:
system "cd directoryfolder"
但是失败了,我也试过使用 system "exit" 来退出终端,但是也失败了。
代码:
chdir('path/to/dir') or die "$!";
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.
system
来完成这些操作的原因是,system
将启动一个新进程,执行你的命令,并返回退出状态。当你调用system "cd foo"
时,你将启动一个shell进程,它将切换到"foo"目录,然后退出。在你的perl脚本中不会发生任何有意义的事情。同样,system "exit"
将启动一个新进程并立即退出。chdir
。对于退出程序,有一个函数exit
。exit
来退出终端会话。cd
是你的shell中的内置命令,exit
也是如此。File::chdir
来实现 cd
。它允许更改工作目录,而这种更改仅在封闭块范围内有效。"wget download.com/download.zip";
system "unzip download.zip"
chdir('download') or die "$!";
system "sh install.sh";
变成:
#!/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
这个需要使用两个非核心模块(而Archive::Extract
只在Perl v5.9.5及其后的版本中成为核心模块),因此您可能需要安装它们。使用cpan
实用程序(或者在AS-Perl上使用ppm
)进行安装。
system
之后、chdir
之前,你漏掉了一个分号。 - Peder Klingenbergsystem
调用组成的Perl脚本应该改为Shell脚本。直接在命令行上尝试以下内容:wget download.com/download.zip; unzip download.zip; cd download; sh install.sh
。 - Peder Klingenberg