如file1:
1 a b c d e f g
2 a b c d e f g
file2:
1 h i j k l m n o p q r s t u v w x y z
2 h i j k l m n o p q r s t u v w x y z
合并为file:
1 a b c d e f g 1 h i j k l m n o p q r s t u v w x y z
2 a b c d e f g 2 h i j k l m n o p q r s t u v w x y z
全部读入数组的方法(比较简单而且很多人都会就不介绍了)有其局限性,因为perl占用的内存空间是字符实际空间的10倍以上。所以读一行写一行是节约内存最有效的方法,所以用Coro::Channel写了个,合并后3M的文本用不了几秒钟感觉速度还可以:
- #!/usr/bin/perl
- use Coro;
- use Coro::Channel;
- my $read_fh1 = new Coro::Channel;
- my $read_fh2 = new Coro::Channel;
- my $result = new Coro::Channel;
- async {
- while () {
- my @str = ($read_fh1->get ,$read_fh2->get);
- chomp(@str);
- my $str_line=join(" ",@str);
- $result->put($str_line);
- }
- };
- open my $FH1, ";
- open my $FH2, ";
- open my $FH, ">>D:/tem/file.txt";
- while ( my $fh1_line = <$FH1> ) {
- $read_fh1->put($fh1_line);
- my $fh2_line = readline($FH2);
- $read_fh2->put($fh2_line);
- my $fh_line = $result->get;
- print $FH "$fh_line\n";
- }
- close $FH1;
- close $FH2;
- close $FH;
生成测试用文本file1、file2代码:
- #!/usr/bin/perl
- #file1(a..g),file2改(h..z)
- my $str=join(" ", (a..g));
- open my $fh,">>file.txt";
- foreach (1..50000){
- print $fh "$_ $str\n";
- }
- close $fh;
最近懒写blog,所以都从QQ空间转文章过来
阅读(1778) | 评论(0) | 转发(0) |