首页 > 代码库 > perl实现从一个文件中随机抽取n行

perl实现从一个文件中随机抽取n行

源码之前,了无秘密,直接上源码:

if(@ARGV!=2){

  die "Usage: $0 sample_file sample_number\n";
}
my($sample_file, $sample_number) = @ARGV;
open my $FILE, "<$sample_file" or die "Can‘t open $sample_file $!\n";
my @content = <$FILE>;
my $all_number = @content;
print STDERR "|$all_number|\n";

my %hits;
my $wl = $sample_number;
for(my $i = 0; $i < $all_number; ++$i){
  if(rand($all_number-$i) < $wl){
    $hits{$i} = 1;
    print STDERR "$wl\n";
    --$wl;
  }
}

my $j = 0;
print STDERR "start\n";
foreach(@content){
  print "$_" if $hits{$j};
  ++$j;
}

print STDERR "done.\n";

原文:http://blog.csdn.net/hongchangfirst/article/details/25126457

作者:hongchangfirst

hongchangfirst的主页:http://blog.csdn.net/hongchangfirst




perl实现从一个文件中随机抽取n行