???有時(shí)候會(huì)需要對大文件進(jìn)行并行處理,但是perl中不像其他的語言贾铝,可以使用多線程,perl的多線程其實(shí)就是對文件進(jìn)行切割垢揩;
而對于文本文件,需要保證行的完整性,一種是快速跳過不需要的行:
#!/usr/bin/perl -w
use strict;
no warnings 'recursion';
my $m=$ARGV[0]; ?#分成m份
my $l=$ARGV[1]; ?#第l份
my $file="test1.txt";
my $line=`wc -l $file`;
my ($linenum)=$line=~/(\d+)/;
my $linenum=10 if(!($linenum));
my $n=int($linenum/$m); ?#每份做n行
open ?READ, "$file" || die $!;
my $i=0;
while (<READ>) {?
? if ($i>=($l-1)*$n){&doit();}
? $i++;
? last if ($i>=$l*$n || $i>linenum)
}
sub doit(){
? print $_;
}
close READ;
好一點(diǎn)的辦法是使用seek镰矿,但是需要處理不完整行,可以讓前一個(gè)進(jìn)程多處理一行秤标,后一個(gè)進(jìn)程少處理一行:
#!/usr/bin/perl -w
use strict;
no warnings 'recursion';
my $m=$ARGV[0]; ?#分成m份
my $l=$ARGV[1]; ?#第l份
my $file="test1.txt";
my @args = stat ?$file;
my $size = $args[7];
my $n=int($size/$m); ? #每份做nbytes
open READ, "<$file" || die $!;
seek READ,(($l-1)*$n),0;
#非第一份,少讀第一行
? if($l>1){
my $tmpline = <READ>;
? }
while (<READ>) {?
? ?&doit();
? ?my $position = tell(READ);
? last if ($position> $l*$n || $position>=$size); #多讀一行?
}
sub doit(){
? print $_;
}
close READ;
perl大文件讀取處理模塊??
?perl CPAN里面的?Tie-File 模塊極大方便了對大文件的操作苍姜。該模塊用perl的數(shù)組代表一個(gè)文件,文件的每一行對應(yīng)數(shù)組的一個(gè)元素衙猪,第一行為元素0,第二回為1垫释,... ?文件本身實(shí)際并不加載到內(nèi)存,對數(shù)組元素的操作立刻作用到文件里棵譬。
最大的方便是可以任意指定處理開頭結(jié)尾的某幾行。
?Tie-File?模塊的基本用法:
#!/usr/bin/perl -w
use strict;
no warnings 'recursion';
use Tie::File;
tie @array, 'Tie::File', filename or die ...;
$array[13] = 'blah'; ? ? # line 13 of the file is now 'blah'
print $array[42]; ? ? ? ?# display line 42 of the file
$n_recs = @array; ? ? ? ?# how many records are in the file?
$#array -= 2; ? ? ? ? ? ?# chop two records off the end
foreach (@array) {
? s/PERL/Perl/g; ? ? ? ? # Replace PERL with Perl everywhere in the file
}
# These are just like regular push, pop, unshift, shift, and splice
# Except that they modify the file in the way you would expect
push @array, new recs...;
my $r1 = pop @array;
unshift @array, new recs...;
my $r2 = shift @array;
@old_recs = splice @array, 3, 7, new recs...;
untie @array; ? ? ? ? ? ?# all finished
還有一個(gè)是Perl中的Thread?模塊:
http://doc.plob.org/perl/perl/PerlThread.html#17_2_1?????