如何使用Perl从大文件中删除非唯一行?

Sub*_*der 3 perl dos batch-file

使用Perl通过Windows中的批处理文件调用重复数据删除Windows中的DOS窗口通过批处理文件调用.批处理文件调用执行操作的Perl脚本.我有批处理文件.只要数据文件不是太大,我工作的代码脚本就会删除重复数据.需要解决的问题是数据文件较大(2 GB或更多),在此文件大小时,尝试将完整文件加载到阵列中以便删除重复数据时会发生内存错误.在以下子程序中发生内存错误: -

@contents_of_the_file = <INFILE>;
Run Code Online (Sandbox Code Playgroud)

(一种完全不同的方法是可以接受的,只要它解决了这个问题,请建议).子程序是: -

sub remove_duplicate_data_and_file
{
 open(INFILE,"<" . $output_working_directory . $output_working_filename) or dienice ("Can't open $output_working_filename : INFILE :$!");
  if ($test ne "YES")
   {
    flock(INFILE,1);
   }
  @contents_of_the_file = <INFILE>;
  if ($test ne "YES")
   {
    flock(INFILE,8);
   }
 close (INFILE);
### TEST print "$#contents_of_the_file\n\n";
 @unique_contents_of_the_file= grep(!$unique_contents_of_the_file{$_}++, @contents_of_the_file);

 open(OUTFILE,">" . $output_restore_split_filename) or dienice ("Can't open $output_restore_split_filename : OUTFILE :$!");
 if ($test ne "YES")
  {
   flock(OUTFILE,1);
  }
for($element_number=0;$element_number<=$#unique_contents_of_the_file;$element_number++)
  {
   print OUTFILE "$unique_contents_of_the_file[$element_number]\n";
  }
 if ($test ne "YES")
  {
   flock(OUTFILE,8);
  }
}
Run Code Online (Sandbox Code Playgroud)

FMc*_*FMc 6

您不必要地存储原始文件的完整副本,@contents_of_the_file并且 - 如果重复数量相对于文件大小较低 - 在%unique_contents_of_the_file和中几乎有两个其他完整副本@unique_contents_of_the_file.如上所述ire_and_curses,您可以通过对数据进行两次传递来降低存储要求:(1)分析文件,存储有关非重复行的行号的信息; (2)再次处理文件以将非重复写入输出文件.

这是一个例子.我不知道我是否选择了散列函数的最佳模块(Digest :: MD5); 也许其他人会对此发表评论.还要注意open()你应该使用的3参数形式.

use strict;
use warnings;

use Digest::MD5 qw(md5);

my (%seen, %keep_line_nums);
my $in_file  = 'data.dat';
my $out_file = 'data_no_dups.dat';

open (my $in_handle, '<', $in_file) or die $!;
open (my $out_handle, '>', $out_file) or die $!;

while ( defined(my $line = <$in_handle>) ){
    my $hashed_line = md5($line);
    $keep_line_nums{$.} = 1 unless $seen{$hashed_line};
    $seen{$hashed_line} = 1;
}

seek $in_handle, 0, 0;
$. = 0;
while ( defined(my $line = <$in_handle>) ){
    print $out_handle $line if $keep_line_nums{$.};
}    

close $in_handle;
close $out_handle;
Run Code Online (Sandbox Code Playgroud)

  • 只要被散列的行是16个字符或更大,这将是一个胜利.如果行长度小于16,则使用行本身代替`%seen`键.我的$ hashed_line =长度($ line)> 15?md5($ line):$ line; 会做的.另请参阅`Bit :: Vector`作为`%keep_line_num`的替代,以减少内存占用. (2认同)