2010-02-02 53 views
6

可能重複:
How do I pass parameters to the File::Find subroutine that processes each file?如何在使用Perl的File :: Find時將參數傳遞給想要的函數?

人們可以使用Perl的File::Find模塊是這樣的:

find(\&wanted, @directories); 

我們如何可以添加一個參數到wanted功能?

例如,我想遍歷/tmp中的文件,從每個文件中提取一些信息,並將結果存儲到不同的目錄中。輸出目錄應該作爲參數給出。

+0

請描述更具體的你正在嘗試做的,我會更新我的答案。 –

+0

另請參閱http://stackoverflow.com/questions/2056649/how-do-i-pass-parameters-to-the-filefind-subroutine-that-processes-each-file –

+0

@ SinanÜnüryour remark http:///stackoverflow.com/questions/2056649/how-do-i-pass-parameters-to-the-filefind-subroutine-that-processes-each-file 解決了我的問題。如果您將它作爲答案發布,我將標記爲已接受 – jojo

回答

10

您使用閉包:

use File::Copy; 

my $outdir= "/home/me/saved_from_tmp"; 
find(sub { copy_to($outdir, $_); }, '/tmp'); 

sub copy_to 
    { my($destination_dir, $file)= @_; 
    copy $file, "$destination_dir/$file" 
     or die "could not copy '$file' to '$destination_dir/$file': $!"; 
    } 
3

File::Find的合同指定將什麼信息傳遞給&wanted

想要的函數不需要參數,而是通過一組變量來完成它的工作。

  • $File::Find::dir是當前目錄名,
  • $_是目錄
  • $File::Find::name內當前文件名是完整的路徑名的文件。

如果你想獲得額外的信息在回調,可以create a sub reference that calls your wanted sub with the desired parameters

+0

謝謝, 我意識到這個選項,但我想知道是否有一些黑客傳遞參數(不使用全局)。 – jojo

4

您可以創建任何您喜歡的代碼引用。您不必使用對指定子例程的引用。有關如何執行此操作的許多示例,請參閱我的File::Find::Closures模塊。我創建了這個模塊來回答這個問題。

+0

這可能適用於我 – jojo

相關問題