Perl Thread中的真实多个文件

时间:2015-05-05 21:17:49

标签: perl

我需要阅读并使用数组中的这么多文件列表进行一些操作。读取概念写在子例程中,文件作为参数传递。下面的代码在一次读取一个文件,程序在读取列表中列出的文件时需要更多次。

我想read_files子例程应该对不同的文件执行多次。

#!/usr/bin/perl
use strict;
opendir DIRS,"/tmp";
my @files=readdir DIRS;
closedir DIRS;

foreach my $file_read(@files){
&read_files($file_read);
}

 sub read_files{
  my $R_file=shift;
  open(INP,"<$R_file");
  my $con=<INP>;
  #some manipulation will go here
  close INP;
 }

1 个答案:

答案 0 :(得分:0)

只要它很简单(我假设你不打算在你的子程序中打印到STDOUT):

use threads;

# create the threads
my @threads = map {threads->create(\&read_files,$_)} @files;

# wait until the threads have finished
foreach my $thread (@threads){
  $thread->join();
}

或者,您可以使用fork,它最容易与Parallel::ForkManager一起使用

你应该看看the documentation for threads,也许是threads tutorial

一点注意事项:使用三个参数打开会好得多。特别是如果您使用插值open