2011-08-10 2 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 행의 구문 오류가 "system"부근에 있습니다. 컴파일 오류로 인해 it.pl이 중단되었습니다. – sirplzmywebsitelol

+1

@sirplzmywebsitelol "압축 해제 줄"은이 문맥에서 의미가 없습니다. 더 많거나 적은 코드 스 니펫으로 질문을 업데이트 할 수 있습니까? –

+0

시스템 "wget ​​http://download.com/download.zip" 시스템 "unzip download.zip" chdir ('download') 또는 죽는 "$!"; 시스템 "sh install.sh"; – sirplzmywebsitelol

14

다음은 system를 호출하여 그 일을 할 수없는 이유 system는, 새로운 프로세스를 시작하여 명령을 실행하고를 반환하는 것입니다 종료 상태. 따라서 system "cd foo"으로 전화를 걸면 쉘 프로세스가 시작되어 "foo"디렉토리로 전환 된 다음 종료됩니다. 어떤 결과도 펄 스크립트에서 발생하지 않습니다. 마찬가지로 system "exit"은 새 프로세스를 시작하고 즉시 다시 종료합니다.

cd 케이스에 대해 원하는 것은 - 바보가 지적한대로 - 기능이 chdir입니다. 프로그램을 종료하려면 함수 exit이 있어야합니다.

그러나 둘 중 어느 것도 터미널 세션의 상태에 영향을 미치지 않습니다. 펄 스크립트가 끝나면 터미널의 작업 디렉토리는 시작하기 전과 동일 할 것이기 때문에 종료 할 수 없습니다 perl 스크립트에서 exit을 호출하여 터미널 세션.

이것은 펄 스크립트가 터미널 쉘과는 별도의 프로세스이므로 다른 프로세스에서 일어나는 일들이 일반적으로 서로 방해하지 않기 때문입니다. 이것은 기능이 아니라 버그입니다.

셸 환경에서 변경하려는 경우 셸에서 이해하고 해석하는 지침을 실행해야합니다. cd은 쉘에 내장 된 명령이며 exit입니다.

3

나는 cd-에 대해 항상 File::chdir을 언급합니다. 그것은 포함하는 블록에 국한되는 작업 디렉토리를 변경할 수 있습니다.

페더가 언급했듯이 스크립트는 기본적으로 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는 펄 v5.9.5 이후에만 된 코어를 가지고) 그래서 당신이 그들을 설치해야 할 수 있습니다. 이렇게하려면 cpan 유틸리티 (또는 AS-Perl의 경우 ppm)를 사용하십시오.

관련 문제