2009-08-19 9 views
1

我有這樣的代碼的下方。如果我在search功能(通過File::Find::find調用)打開文件$File::Find::name(在這種情況下,它是./tmp/tmp.h),它說:「無法打開文件./tmp/tmp.h原因=在temp.pl行沒有這樣的文件或目錄第36行,第98行。「如何打開由想要的函數內的File :: Find找到的文件?

如果我直接在另一個函數打開文件,我可以打開該文件。 有人可以告訴我這種行爲的原因嗎?我在Windows上使用activeperl,版本是5.6.1。

use warnings; 
use strict; 
use File::Find; 

sub search 
{ 
    return unless($File::Find::name =~ /\.h\s*$/); 
    open (FH,"<", "$File::Find::name") or die "cannot open the file $File::Find::name reason = $!"; 
    print "open success $File::Find::name\n"; 
    close FH; 

} 

sub fun 
{ 
    open (FH,"<", "./tmp/tmp.h") or die "cannot open the file ./tmp/tmp.h reason = $!"; 
    print "open success ./tmp/tmp.h\n"; 
    close FH; 

} 

find(\&search,".") ; 
+1

我剛剛使用你的代碼,它對我來說工作正常。你是否在使用其他代碼? – Space 2009-08-19 09:36:51

+0

@Octopus,相同的代碼。 – chappar 2009-08-19 09:40:09

+1

兩點意見:第一行更改爲1)'回報,除非/ \^h \ S * $ /'爲了簡潔和清晰。當然,你也可能希望做不區分大小寫的匹配,我不知道爲什麼你要接受文件名後的空格。 2)不需要在'open'調用中引用'$ File :: Find :: name'。 – 2009-08-19 10:42:36

回答

10

請參閱perldoc File::Find:在File::Find::find更改爲當前搜索的目錄後,將調用想要的函數(在您的情況下搜索)。如您所見,$File::Find::name包含文件相對於搜索開始位置的路徑。該路徑在當前目錄更改後不起作用。

你有兩個選擇:

  1. 泰爾文件::查找不改變其搜索目錄:find({ wanted => \%search, no_chdir => 1 }, '.');
  2. 或者不使用$File::Find::name,但$_代替。
0

如果./tmp/是一個符號鏈接,那麼你需要做以下幾點:

find({ wanted => \&search, follow => 1 }, '.'); 

這是否幫助?

+0

他在Windows上。我懷疑這與符號鏈接有關。 – 2009-08-19 10:26:28

+0

open()在Windows上使用正斜槓嗎?回覆:符號鏈接 - 掛載的UNIX/Linux共享怎麼樣?會自動從Windows中遵循符號鏈接? – draegtun 2009-08-19 10:59:53

+0

@draegtun是的,'open'確實與正斜槓一起工作。 ' 「TMP/tmp.h」'優選' 「TMP \\ tmp.h」'(我喜歡'文件::規格:: catfile')。我不知道你的第二個問題的答案。 – 2009-08-19 11:23:05

-1

如果要在當前工作目錄中搜索文件,可以使用Cwd。

use warnings; 
use strict; 
use File::Find; 
use Cwd; 

my $dir = getcwd; 

sub search 
{ 
    return unless($File::Find::name =~ /\.h\s*$/); 
    open (FH,"<", "$File::Find::name") or die "cannot open the file $File::Find::name reason = $!"; 
    print "open success $File::Find::name\n"; 
    close FH; 

} 

find(\&search,"$dir") ; 
+0

這可能實際上工作,因爲getcwd將返回一個絕對路徑。但你的答案肯定需要更多的解釋。 – innaM 2009-08-19 10:12:29

相關問題