加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 23:53:38 所属栏目:大数据 来源:网络整理
导读:源码之前,了无秘密,直接上源码: if(@ARGV!=2){ ? die "Usage: $0 sample_file sample_numbern"; } my($sample_file,$sample_number) = @ARGV; open my $FILE,"$sample_file" or die "Can't open $sample_file $!n"; my @content = $FILE; my $all_numbe

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

if(@ARGV!=2){

? die "Usage: $0 sample_file sample_numbern";
}
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 "$wln";
? ? --$wl;
? }
}

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

print STDERR "done.n";

原文:http://www.voidcn.com/article/p-ozgsrdev-baq.html

作者:hongchangfirst

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读