2010-01-08 73 views
0

我需要從傳遞給Perl腳本的路徑中獲取目錄名作爲運行時參數。 這裏是我使用的代碼:如何從Perl中的DOS中獲取目錄列表?

$command ="cd $ARGV[0]"; 
system($command); 

$command="dir /ad /b"; 
system($command); 
@files=`$command`; 

但它仍返回目錄內的目錄名我從中運行此Perl腳本。 簡而言之,如何從路徑傳遞給此Perl腳本的目標目錄獲取目錄名稱?

+5

儘管它完全是你的選擇,但我仍然建議不要使用類似這樣的系統調用,因爲Perl有內置的方法來做到這一點。你讓你的代碼不能移植。 – ghostdog74 2010-01-08 06:46:49

回答

2

這也應該工作
$command = "dir /ad /b $ARGV[0]" ;

+0

:D 我用了類似的東西。 – fixxxer 2010-01-08 07:58:31

9

從你試圖在你的問題做了命令行

c:\test> perl myscript.pl c:\test 

這樣做有目錄的列表的其他方法上張貼

$dir = $ARGV[0]; 
chdir($dir); 
while(<*>){ 
chomp; 
# check for directory; 
if (-d $_) { 
    print "$_\n" ; 
} 
} 

判斷。看到這些從文檔

  1. perldoc -f opendirperldoc -f readdir

  2. perldoc perlopentut

  3. perldoc -f glob

  4. perldoc perlfunc(看運營商的測試文件。-x-d-f等)

+0

幾行代碼將非常有幫助。 – fixxxer 2010-01-08 05:57:41

+0

所以這是文檔。 – 2010-01-08 17:11:20

2

您的問題是,通過「系統」運行「cd」不會更改perl進程的工作目錄。要做到這一點,使用 「CHDIR」 功能:

chdir($ARGV[0]); 

$command="dir /ad /b"; 
system($command); 
@files=`$command`; 
+3

爲了澄清,問題代碼中的'system'開始一個子進程,即'cd',其中__does__改變__its自己的工作目錄。然後子進程結束;但環境變化(如工作目錄和環境變量)對父進程(即Perl腳本)沒有影響。 – daxim 2010-01-08 09:45:52

0

使用File::DosGlob(核心,因爲之前的Perl V5.5),以避免像跳過文件陷阱匹配/^\ ./。

perl -MFile::DosGlob=glob -lwe "chdir 'test_dir'; print for grep {-d} <*>" 
相關問題