如何使用perl进入目录?

7
我在尝试以下操作: system "cd directoryfolder" 但是失败了,我也试过使用 system "exit" 来退出终端,但是也失败了。
3个回答

25

代码:

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.

我在解压缩代码后输入了一行'chdir('folder01') or die "$!";',但是我收到了以下错误信息。 it.pl的第6行语法错误,附近有“system” 由于编译错误,it.pl的执行被中止。 - sirplzmywebsitelol
1
@sirplzmywebsitelol 您的“解压行”在此情境下没有意义。您能否更新您的问题,提供更为完整的代码片段,以便我们看到您尝试做什么? - Peder Klingenberg
系统 "wget http://download.com/download.zip" 系统 "unzip download.zip" chdir('download') or die "$!"; 系统 "sh install.sh"; - sirplzmywebsitelol
system 之后、chdir 之前,你漏掉了一个分号。 - Peder Klingenberg
1
顺便说一下,一个几乎完全由system调用组成的Perl脚本应该改为Shell脚本。直接在命令行上尝试以下内容:wget download.com/download.zip; unzip download.zip; cd download; sh install.sh - Peder Klingenberg
Perl的Archive::Extract可以帮助您通过系统调用直接从程序中解压缩文件。 - brian d foy

14
你不能通过调用system来完成这些操作的原因是,system将启动一个新进程,执行你的命令,并返回退出状态。当你调用system "cd foo"时,你将启动一个shell进程,它将切换到"foo"目录,然后退出。在你的perl脚本中不会发生任何有意义的事情。同样,system "exit"将启动一个新进程并立即退出。
对于cd情况,你想要的是像bobah所指出的那样,使用函数chdir。对于退出程序,有一个函数exit
然而,这两个函数都不会影响你所在的终端会话状态。当你的perl脚本结束后,终端的工作目录与你开始之前一样,你也无法通过在perl脚本中调用exit来退出终端会话。
这是因为你的perl脚本是和你的终端shell分离的进程,分离的进程通常不会相互干扰,这是一种特性而不是错误。
如果你想要在你的shell环境中改变东西,你必须发出可被你的shell理解和解释的指令。cd是你的shell中的内置命令,exit也是如此。

5
我一直喜欢提到 File::chdir 来实现 cd。它允许更改工作目录,而这种更改仅在封闭块范围内有效。
正如Peder所提到的,你的脚本基本上是将所有系统调用与Perl绑在一起。我提供了更多的Perl实现。
"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)进行安装。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接