2009-11-13 115 views
1

當我嘗試使用文件句柄作爲參數的「chdir」時,「chdir」返回0,並且pwd仍返回相同的目錄。應該是這樣嗎?爲什麼我的chdir文件句柄在Perl中不起作用?

我想這一點,因爲文檔CHDIR我發現:

「在支持fchdir系統,你 可能傳遞一個文件句柄或目錄 句柄作爲參數在系統是 不要」 t支持fchdir,傳遞句柄 在運行時會產生致命錯誤。「後來

考慮:

#!/usr/bin/perl -w 
use 5.010; 
use strict; 
use Cwd; 

say cwd(); # /home/mm 
open(my $fh, '>', '/home/mm/Documents/foto.jpg') or die $!; 
say chdir $fh; # 0 
say cwd(); # /home/mm 

我原以爲這也許CHDIR到文件的目錄 - 但沒有DWIM我在這裏。

+0

這是哪種語言/環境? – unwind 2009-11-13 16:45:58

+0

perl 5.10.0/linux – 2009-11-13 17:12:44

+0

你的小演示腳本顯示問題在哪裏? – 2009-11-13 20:24:58

回答

8

它還說

 
It returns true upon success, false otherwise. 

也就是說你到chdir調用失敗。檢查$!變量以瞭解發生了什麼事情的線索。由於您沒有收到致命的運行時錯誤,因此您不必擔心有關fchdir的最後一段。


跑了幾個測試,我看到chdir FILEHANDLE作品時FILEHANDLE指的是一個目錄,而不是一個普通的文件。希望幫助:

open(FH, "<", "/tmp/file"); # assume this file exists 
    chdir FH and print "Success 1\n" or warn "Fail 1: $!\n"; 
    open(FH, "<", "/tmp"); 
    chdir FH and print "Success 2\n" or warn "Fail 2: $!\n"; 
    opendir(FH, "/tmp"); 
    chdir FH and print "Success 3\n" or warn "Fail 3: $!\n"; 

 

Fail 1: Not a directory 
    Success 2 
    Success 3 
+0

Tsk tsk,你使用的是一個全局的typeglob而不是本地的詞法:) – Ether 2009-11-13 17:12:27

+0

我不知道,那個文件句柄可以指向一個目錄。 – 2009-11-13 17:14:14

+0

@sid_com這不是一個有用的功能,但在某個抽象層次上,Un * x目錄僅僅是另一個文件 – mob 2009-11-13 17:18:36

0

perl哪個版本?哪個操作系統?

5.10.1在Windows上:

#!/usr/bin/perl 

use strict; use warnings; 

# have to use a file because Windows does not let 
# open directories as files 
# only done so I can illustrate the fatal error on 
# a platform where fchdir is not implemented 

open my $fh, '<', 'e:/home/test.txt' 
    or die "Cannot open file: $!"; 

chdir $fh 
    or die "Cannot chdir using filehandle: $!"; 

輸出:

 
C:\Temp> k 
The fchdir function is unimplemented at C:\Temp\k.pl line 9. 

5.10.1在Linux(/home/sinan/test是一個目錄):

$ cat k.pl 
#!/usr/bin/perl 

use strict; use warnings; 

use Cwd; 

open my $fh, '<', '/home/sinan/test' 
    or die "Cannot open file: $!"; 

chdir $fh 
    or die "Cannot chdir using filehandle: $!"; 

print getcwd, "\n"; 

$ ./k.pl 
/home/sinan/test 
0

爲我工作。 Windows不支持fchdir,它實際上是一個致命錯誤:

perl -we"opendir my $fh, 'temp'; chdir $fh or print 'foo'" 

產生致命錯誤。所以它看起來就像在根本不支持fchdir的系統上一樣。看起來措辭可能被清除,特別是「可能」一詞。

相關問題