2011-08-10 406 views

回答

22

代碼:

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. 
+0

我輸入了'chdir('folder01')或者'$!';''我的解壓縮行後,但我得到以下錯誤。 語法錯誤it.pl第6行,靠近「系統」 執行it.pl因編譯錯誤而中止。 – sirplzmywebsitelol

+1

@sirplzmywebsitelol你的「解壓縮行」在這種情況下沒有意義。你可以用一個或多或少的完整的代碼片段來更新你的問題,所以我們可以看到你想要做什麼? –

+0

system「wget http://download.com/download.zip」 system「unzip download.zip」 chdir('download')or die「$!」; 系統「sh install.sh」; – sirplzmywebsitelol

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一樣。

3

我總是喜歡提File::chdircd -ing。它允許更改封閉塊本地的工作目錄。

正如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)執行此操作。