我想从一个文件写入多个文件而不使用数组来消除复杂性

时间:2018-11-27 04:21:45

标签: perl

我想从一个文件写入多个文件(每次都获取最新数据),而无需使用数组来消除复杂性。我已经使用数组尝试过了,但是当数据多于它会减慢该过程的速度。

请给我一些提示,我将如何消除程序的复杂性。

输入:从目录中读取文本文件。

输出:

File1.pl - 1 2 3 4 5 6
File2.pl - 6 7 8 9 10
File3.pl -11 12 13 14 15
File4.pl -16 17 18 19 20

我使用数组来做到这一点:

use feature 'state';
open (DATA,"<","e:/today.txt");
@array=<DATA>;
$sizeofarray=scalar @array;

print "Total no. of lines in file is :$sizeofarray";
$count=1;
while($count<=$sizeofarray)
{
    open($fh,'>',"E:/e$count.txt");
    print $fh "@array[$count-1..($count+3)]\n";
    $count+=5;
}

2 个答案:

答案 0 :(得分:4)

将行存储在一个小的缓冲区中,每隔五行打开一个文件,并将缓冲区写入其中

use warnings;
use strict;
use feature 'say';

my $infile = shift || 'e:/today.txt';

open my $fh_in, '<', $infile or die "Can't open $infile: $!";

my ($fh_out, @buf);

while (<$fh_in>) {
    push @buf, $_; 
    if ($. % 5 == 0) {
        my $file = 'e' . (int $./5) . '.txt';
        open $fh_out, '>', $file  or do {
            warn "Can't open $file: $!";
            next;
        };
        print $fh_out $_ for @buf;
        @buf = (); 
    }
}

# Write what's left over, if any, after the last batch of five
if (@buf) {
    my $file = 'e' . ( int($./5)+1 ) . '.txt';
    open $fh_out, '>', $file or die "Can't open $file: $!";
    print $fh_out $_ for @buf;
}

答案 1 :(得分:1)

我从您的代码中观察到,您可以尝试

  use warnings;
  use strict;
  open (my $fh,"<","today.txt") or die "Error opening $!";

  my $count = 1;
  while(my $line = <$fh>)
  {
     open my $wh,'>',"e$count.txt" or die "Error creating $!";
     print $wh $line;
     for(1..4){
        if(my $v = scalar <$fh>){
           print $wh  $v ;
        }
        else{
           last ;
        }
     }
     $count++;
  }