假设有一个名为"input.txt"的文本文件,其内容如下:
some field1a | field1b | field1c
...another approx 1000 lines....
fielaNa | field Nb | field Nc
我可以选择任何字段分隔符。
需要一个脚本,在每次离散运行时从此文件中获取一个唯一(不重复)的随机行,直到使用所有行。
我的解决方案:我在文件中添加了一列,所以有
0|some field1a | field1b | field1c
...another approx 1000 lines....
0|fielaNa | field Nb | field Nc
然后用以下代码处理它:
use 5.014;
use warnings;
use utf8;
use List::Util;
use open qw(:std :utf8);
my $file = "./input.txt";
#read all lines into array and shuffle them
open(my $fh, "<:utf8", $file);
my @lines = List::Util::shuffle map { chomp $_; $_ } <$fh>;
close $fh;
#search for the 1st line what has 0 at the start
#change the 0 to 1
#and rewrite the whole file
my $random_line;
for(my $i=0; $i<=$#lines; $i++) {
if( $lines[$i] =~ /^0/ ) {
$random_line = $lines[$i];
$lines[$i] =~ s/^0/1/;
open($fh, ">:utf8", $file);
print $fh join("\n", @lines);
close $fh;
last;
}
}
$random_line = "1|NO|more|lines" unless( $random_line =~ /\w/ );
do_something_with_the_fields(split /\|/, $random_line))
exit;
这是一种可行的解决方案,但不太好,因为:
- 每次运行脚本时,行顺序都会改变
- 不支持并发脚本运行。
如何更有效、更优雅地编写它?